Search code examples
reactjsreact-reduxreact-routerconnected-react-router

Refresh a page in a single page application


Let's say that you receive a link that takes you to a page from a single page application. You want to be able to see that page instantly (of course, if you are logged in).

The issue is that the data is not fetched from the server, so the page is empty.

Which practice is the best to fetch all the necessary data to be able to see that page correctly?. Basically, when refreshing the page, you want to remain in that place, not to be redirected to "/"(for example).

I thought about making a separate component which fetch all the data and when its all done, render the page. But, it comes with a downside, which is double fetching of data on normal usage of application.


Solution

  • With a single page application you shouldn't have to manually refresh the page yourself. I would consider using react-router for navigation within your single page application. Furthermore, when a particular view (React Component) needs more data to be properly displayed I would leverage the componentDidMount() lifecycle. Within componentDidMount() you can fetch the necessary data with Axios or with the browser's built in fetch api. Ideally, you shouldn't be fetching your entire application at once, and your React components are modular in nature. As an example of how to leverage the Axios library one could do something along the lines of:

    1. Install axios:

      npm install -S axios yarn add axios

    2. Fetch the necessary data for your react component using the componentDidMount() lifecycle method:

    React component:

    componentDidMount(){ // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success: i.e. set your state so you can use your data console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); }

    Hopefully that helps!