0
votes

I'm relatively new to Reactjs and I've got little dilemma here. I'm using Draftjs as a WYSIWYG editor in a simple app. When receiving data from an API (as you normally would) then passing it to a child component via props, I'm having issue to update EditorState. I assume I need to create EditorState as such at the beginning:

componentWillMount() {
   this.setState({editorState: EditorState.createEmpty()});
}

Then when I received props from an API I'd like to update the EditorState with the props received. So in my head and ideal world I'd do something like this:

componentWillReceiveProps() {
   let processedHTML = DraftPasteProcessor.processHTML(this.props.text);
   let contentState = ContentState.createFromBlockArray(processedHTML);

   this.setState({editorState: EditorState.createWithContent(contentState)});
}

But that doesn't seem to be the case. ComponentWillReceiveProps() as I was reading up online doesn't wait until props have updated to the value passed from an API, ComponentWilLReceiveProps() runs before data from an API is received and I get the following error:

Cannot read property 'trim' of undefined DraftJS

Anyone with a little more experience in Reactjs could advise me on this? How to update EditorSTate when the information is received from an API. Maybe its worth noting, this is how I pass data to the component from parent.

<WysiwygEditor full={true} text={this.props.error.errorText}/>
1
I'm not sure I completely understand the issue, but for what it's worth, the initial state should be assigned in the constructor, not in componentWillMount.Or B
The issue is this.props.text is undefined at the time component is initialised, therefore I get above errorTSlegaitis

1 Answers

0
votes

componentWillReceiveProps takes an argument that gives the next props, you should use it because this.props in this method will give you the "previous" props.

componentWillReceiveProps(nextProps) {
    if (this.props.text !== nextProps.text) {
       let processedHTML = DraftPasteProcessor.processHTML(nextProps.text);
       let contentState = ContentState.createFromBlockArray(processedHTML);
       this.setState({editorState: EditorState.createWithContent(contentState)});
    }
}

I also added a condition to be sure you are updating the text only on the text changes.