I am working on a project using React Router, and I'm having some problems with the data flow.
On every page there is an AJAX call that gets the data for the ponent. I have been putting them in ponentDidMount
:
// Below code is written in ES6
ponentDidMount(){
$.get(someURL, (data)=>{
this.setState({data:data})
})
}
Although this works on initial load, it does not get called again when the url changes (a manual refresh is needed). I cannot seem to find a proper life cycle to place the AJAX calls.
Someone please enlighten me with the proper approach to getting data in React Router.
I am working on a project using React Router, and I'm having some problems with the data flow.
On every page there is an AJAX call that gets the data for the ponent. I have been putting them in ponentDidMount
:
// Below code is written in ES6
ponentDidMount(){
$.get(someURL, (data)=>{
this.setState({data:data})
})
}
Although this works on initial load, it does not get called again when the url changes (a manual refresh is needed). I cannot seem to find a proper life cycle to place the AJAX calls.
Someone please enlighten me with the proper approach to getting data in React Router.
Share Improve this question asked May 16, 2015 at 19:19 BenBen 1,56813 silver badges30 bronze badges 1- I know, this is old but.. check this one: stackoverflow./questions/30279786/… – ridermansb Commented Mar 21, 2017 at 22:45
1 Answer
Reset to default 19After a bit of searching around, this README ultimately solves the problem.
There are 2 solutions outlined in the document:
Use
addHandlerKey={true}
:<Route handler={User} path="/user/:userId" addHandlerKey={true} />
Use
ponentWillReceiveProps
instead ofponentDidMount
.- I ended up using both,
ponentDidMount
for the initial load,ponentWillReceiveProps
for subsequent ones. - Since they share the same code, I created a new function
_updateState
and called it in both lifecycles.
- I ended up using both,
My code now:
class Classes extends React.Component {
ponentDidMount(){ this._updateState() }
ponentWillReceiveProps(){ this._updateState() }
_updateState(){
$.get(/*Some URL*/, (data)=>{
this.setState({data:data})
})
}
}