prisoner_of_azkaban
prisoner_of_azkaban

Reputation: 758

Fetch new data when the component props change

I have 4 buttons and upon clicking the button a component is called where I show different data based on which button was clicked.

For the first time when I click the button, that component's constructor and componentWillMount() function is called but after that, It's not called until I refresh the page or navigate to different page and come back.

So, Is there any way to call the component's componentWillMount() function or constructor each time that particular component is called?

I am not attaching code as the question is pretty straight-forward.

Upvotes: 3

Views: 2180

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 282050

Its looks like that You are supplying different props to the component and hence you need to make use of componentWillReceiveProps together with componentDidMount

According to the documentation

componentWillReceiveProps(nextProps)

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

So you need to update check if your props have changed in the child components componentWillReceiveProps and take action based on it. Since componentWillReceiveProps is not called the first time the component is mounted you need to make use of componentDidMount as well since it is called only on the first render

Upvotes: 4

Simmetric
Simmetric

Reputation: 1681

No, as the documentation states the component is only mounted once in the page lifecycle.

I think you probably need the componentWillUpdate event instead. Make sure the shouldComponentUpdate method returns true when needed.

Upvotes: 1

Related Questions