简体   繁体   中英

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.

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: ie 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!

As @Nathan pointed out, it is a bad practice to refresh a single page application.

I would recommend checking whether the data variables are undefined (in case of controlled components, props) and based on that return either a (to show that the page is still loading) component or a

eg if(!this.props) return ; //null in case if you want to display a //white-page return ;

Hope this clarifies it! Happy Coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM