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 component. I have been putting them in componentDidMount
:
// Below code is written in ES6
componentDidMount(){
$.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.
You can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window. fetch.
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. Let us create a simple application to React to understand how the React Router works.
React Router plays an important role to display multiple views in a single page application. Without React Router, it is not possible to display multiple views in React applications. Most of the social media websites like Facebook, Instagram uses React Router for rendering multiple views.
At the core of every React Router application should be a router component. For web projects, react-router-dom provides <BrowserRouter> and <HashRouter> routers. The main difference between the two is the way they store the URL and communicate with your web server. A <BrowserRouter> uses regular URL paths.
After 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 componentWillReceiveProps
instead of componentDidMount
.
componentDidMount
for the initial load, componentWillReceiveProps
for subsequent ones._updateState
and called it in both lifecycles.My code now:
class Classes extends React.Component {
componentDidMount(){ this._updateState() }
componentWillReceiveProps(){ this._updateState() }
_updateState(){
$.get(/*Some URL*/, (data)=>{
this.setState({data:data})
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With