Search code examples
javascriptreactjsdraftjs

ReactJS receiving data from API passing it as props to DraftJS


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}/>

Solution

  • 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.