简体   繁体   中英

Fetch data only once to React App. Never fetch again after page reloads

I'm wondering if it's possible to fetch data only once to a running React app. The goal that I want to achieve is this: I have an app where I'm fetching user data from JSONPLACEHOLDER API, then passing this data to the state of this component and assigning to a usersArray variable.

During app is running there are some actions proceeded like deleting data from this usersArray.

WHAT IS HAPPENING:

After the page reloads, the main component is mounting once again and the data is fetched once again.

EXPECTATION :

I want to fetch this data only once and forever. Is it possible somehow to achieve this thing in React or I'm doing something wrong ?

You could put the data in localStorage and always check if there is some data there before doing the request.

Example

class App extends React.Component {
  state = { users: [] };

  componentDidMount() {
    let users = localStorage.getItem("users");

    if (users) {
      users = JSON.parse(users);
      this.setState({ users });
    } else {
      fetch("https://jsonplaceholder.typicode.com/users")
        .then(res => res.json())
        .then(users => {
          this.setState({ users });
          localStorage.setItem("users", JSON.stringify(users));
        });
    }
  }

  handleClick = index => {
    this.setState(
      prevState => {
        const users = [...prevState.users];
        users.splice(index, 1);
        return { users };
      },
      () => {
        localStorage.setItem("users", JSON.stringify(this.state.users));
      }
    );
  };

  render() {
    return (
      <div>
        {this.state.users.map((user, index) => (
          <div key={user.id}>
            <span>{user.name}</span>
            <button onClick={() => this.handleClick(index)}>Remove</button>
          </div>
        ))}
      </div>
    );
  }
}

You can use session storage if you want the data to be retrieved once PER SESSION or local storage if you want to have better control of the data's "expiration". set an arbitrary value in the fetch's callback that you'll check before fetching another time every time the app loads. The window.sessionStorage API is simple to use :

sessionStorage = sessionStorage || window.sessionStorage

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();

Same syntax is used for window.localStorage

This is absolutely right :-

After the page reloads, the main component is mounting once again and the data is fetched once again.

As from my understanding , when you delete and then refresh then deleted data comes back. This is off course going to happen as everything is getting stored in memory.

Solution :- You must use database , when you save data you do it in db , when you delete data , you delete it from db & when you fetch data then you fetch from db.

So any operation like update , delete will work fine now.

The question is WHY you expecting sth different?

It's only fake api, real would work as expected. If you're correctly sending change/delete requests - they will be memorized and refresh will read updated data (if not cached).

If it's a SPA (Single Page App) there is no need for refresh - it shouldn't happen. Maybe sth went wrong with router?

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