Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router where to use AJAX

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.

like image 975
Ben Avatar asked May 16 '15 19:05

Ben


People also ask

Can AJAX be used with react?

You can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window. fetch.

Why we use BrowserRouter in react?

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.

Does Facebook use react Router?

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.

What is the difference between BrowserRouter and Router in react?

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.


1 Answers

After a bit of searching around, this README ultimately solves the problem.

There are 2 solutions outlined in the document:

  1. Use addHandlerKey={true}:

    <Route handler={User} path="/user/:userId" addHandlerKey={true} />

  2. Use componentWillReceiveProps instead of componentDidMount.

    • I ended up using both, componentDidMount for the initial load, componentWillReceiveProps for subsequent ones.
    • Since they share the same code, I created a new function _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})
    })
  }
}
like image 92
Ben Avatar answered Oct 12 '22 00:10

Ben