Search code examples
reactjslocal-storagereact-navigationreact-props

How to save state of React page on reload or redirecting back/ forward?


Below is my code. I am consuming an API and getting some data on the current page. Now I want to save this page's state when I reload the page or go back or go forward again.

Here, I am getting featureGroupID from previous page api and storing here in global variable customerID.

I know it is done using local Storage but since I am extremely new on Reactjs, I dont know how to preserve the state. Can someone help?

class CustomerList extends Component {
  state = {
    isLoading: true,
    users: [],
    error: null,
    customerID: null
    };
    componentDidMount() {
      fetch('http://localhost:8080/entity/getEntityByFeatureGroup/'+this.customerID)
      .then(response => response.json())
      .then(data =>
       this.setState({
       users: data,
       isLoading: false,
    })
      ).catch(error => this.setState({ error, isLoading: false }));
	}
    render() {		
		var logTable = this.props;
		console.log(logTable);
      var customerColumnList = this.props;
      this.customerID = customerColumnList.location.aboutProps.id.featureGroupID;
      var headerName = customerColumnList.location.aboutProps.name.logTable.headerName;    
    const { isLoading, users, error } = this.state;
    return (....


Solution

  • you can use localStorage.setItem and localStorage.getItem for accessing local storage. like:

    class CustomerList extends Component {
      state = {
        isLoading: true,
        users: [],
        error: null,
        customerID: null
        };
        componentDidMount() {
         if(!localStorage.getItem('customerlist-data')) {
            
    fetch('http://localhost:8080/entity/getEntityByFeatureGroup/'+this.customerID)
          .then(response => response.json())
          .then(data => {
           this.setState({
           users: data,
           isLoading: false,
        });
           localStorage.setItem('customerlist-data', data);
          }
          ).catch(error => this.setState({ error, isLoading: false }));
         enter code here}          
        }
        render() {      
            var logTable = this.props;
            console.log(logTable);
          var customerColumnList = this.props;
          this.customerID = customerColumnList.location.aboutProps.id.featureGroupID;
          var headerName = customerColumnList.location.aboutProps.name.logTable.headerName;    
        const { isLoading, users, error } = this.state;
        return (....