简体   繁体   中英

How to persist data in react app to minimize server call

In one of my ReactJS page, there are two dropdown menu's, on selecting the value of one or the other, it makes server API call to fetch the data. To fetch the data, i am using useEffect hook as below

export const useFetch = () => {
const [state, setState] = useState({ data: null, loading: true });

useEffect(() => {
setState(state => ({ data: state.data, loading: true }));
fetch(url)
  .then(x => x.text())
  .then(y => {
    setState({ data: y, loading: false });
  });
}, []);

return state;
};

Now, from the drop-down menu's, there are certain number of combinations which can be made to fetch the API data, as the same are not too big with options and for any combination, the value from API is gonna constant, so i need to prevent the API call, if the same combination data had been fetched before and utilize the previous ones only and minimize my component re rendering (this is also one situation if the route changes and it comes back).

Please suggest how to approach in this situation. I have researched on browser's localstorage but cleaning the localstorage values will be a little problematic if the browser/tab closes, etc

  • If you want the data retained on app startup use Redux
  • If you want the data retained for the whole session use sessionStorage (will be erased once the browser window is closed)
  • If you want the data retained as long is valid use localStorage, in case of need you can clear the storage on beforeUnload event

Example:

  componentDidMount() {
    window.addEventListener('beforeunload', this.handleBeforeunload)
  }

  componentWillUnmount() {
    window.removeEventListener('beforeunload', this.handleBeforeunload)
  }

  handleBeforeunload() {
      localStorage.removeItem('myItem')
  }

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