db14
db14

Reputation: 117

How to update child component after props are changed in parent component

I have component TopicsView where I have property called choosenTopicId which I change on button click. Inside this component I have child component

<TopicViewOnSide TopicId={this.state.choosenTopicId} />

Inside TopicViewOnSide I use TopicId in componentDidMount() when I'm sending request from axios (HTTP GET) to get topic data from the server and then component TopicViewOnSide renders. My problem is when I change choosenTopicId by clicking button in TopicView, props are changed and it's good. But the child component doesn't rerender when the props are changed and I have old topic data because the child component didn't call componentDidMount() and there was no request to server. Can I somehow call the method componentDidMount() when the props are changed so the request from axios will be send and my data will be updated ?

Upvotes: 0

Views: 1576

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

You're looking for componentDidUpdate() which gets triggered after every state or prop change. The componentDidMount() method only runs a single-time.

You can do something like:

componentDidUpdate(prevProps){ 
   if(this.props.blaw !== prevProps.blaw){
     ...execute your logic 
   }
} 

That creates a check to do something only when props change.

Upvotes: 2

Related Questions