1

I am doing a simple todo-app where I tried to render an EditComponent based on the id of the note clicked so that I could populate the existing details in the edit note form. I am storing the active note id in Parent's state. For the first time when EditComponent is rendered, it works as expected. However, when I change the id using setState, the existing render is not getting updated with new note details. This is the function which gets executed when a particular note's edit button is clicked

  setEditState = id => {
    this.setState({id,isEdit:true})
  }

Here's my Parent render()

render() {
    let form;
    if(this.state.isEdit){
      form = <EditComponent id={this.state.id} />
    }
    else{
      form = <AddComponent />
    }
    return (
      <div className="App">
        <ViewComponent notes={this.state.notes} setEditState={this.setEditState} deleteNote={this.deleteNote} />
        {form}
      </div>
    );
  }

Here's where I'm populating the EditComponent state.

    async componentDidMount(){
        const note = await this.getNote(this.props.id)
        console.log(note.data.subject)
        this.setState({
            id:this.props.id,
            modifiedSubject: note.data.subject,
            modifiedNote: note.data.noteText
        })
    }

This is one of the inputs in edit form in child render()

<input className="form-control" type="text" onChange={this.handleSubject} value={this.state.modifiedSubject} />

My hunch: Am I not getting it updated again and again because I'm using componentDidMount()? If so, is there any lifecycle method which executes when the prop passed to child changes?

Thanks in advance

  • `componentDidMount` is only called the first time the component is rendered. If you need to react to prop changes, have a look at https://reactjs.org/docs/react-component.html#componentdidupdate – Felix Kling Oct 07 '20 at 13:44
  • Please attach the rest of EditComponent and parent component – Nikko Khresna Oct 07 '20 at 13:47

1 Answers1

-1

You have to use UNSAFE_componentWillReceiveProps() for it.

Ref

maya_nk99
  • 502
  • 3
  • 5
  • That method was renamed to `UNSAFE_componentWillReceiveProps` and is deprecated. https://reactjs.org/docs/react-component.html#updating – Felix Kling Oct 07 '20 at 13:46