How to cache fetched data in react without redux
You can cache with:-
1) Local Storage
2) Redux Store
3) Keep data between mouting and unmounting
import React, { Component, PropTypes } from 'react';
// Set initial state
let state = { counter: 5 };
class Counter extends Component {
constructor(props) {
super(props);
// Retrieve the last state
this.state = state;
this.onClick = this.onClick.bind(this);
}
componentWillUnmount() {
// Remember state for the next mount
state = this.state;
}
onClick(e) {
e.preventDefault();
this.setState(prev => ({ counter: prev.counter + 1 }));
}
render() {
return (
<div>
<span>{ this.state.counter }</span>
<button onClick={this.onClick}>Increase</button>
</div>
);
}
}
export default Counter;
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;