How to cache fetched data in react without redux

Den Gas picture Den Gas · Mar 30, 2018 · Viewed 18.3k times · Source

I know, using Redux I have common store and when I change my location, for example I went from /videos page, but I still have fetched videos in my videos reducer. So if I then decide to go back to my videos page I show user already loaded videos from my store, and will load more if he needs and store them.

But in React without Redux if I change my location /videos where I fetched some videos and then stored them in my local state of my VideosPage component and then went back to this page, I have no videos anymore and should fetch them from scratch.

How can I cache them and is it possible at all?

PS: This is more theoretical question so no code provided.

Answer

Shubham Khatri picture Shubham Khatri · Mar 30, 2018

The best way to save data when you want to repopulate it at a later point of time is to save it in localStorage, which allows you to get the data even after refreshing the app

const InitialState = {
   someState: 'a'
}
class App extends Component {

 constructor(props) {
  super(props);

  // Retrieve the last state
  this.state = localStorage.getItem("appState") ? JSON.parse(localStorage.getItem("appState")) : InitialState;

}

componentWillUnmount() {
  // Remember state for the next mount
  localStorage.setItem('appState', JSON.stringify(this.state));
}

render() {
  ...
 }
}

export default App;