DEV Community

Cover image for Using Window.localStorage with React
Rossano D'Angelo
Rossano D'Angelo

Posted on

Using Window.localStorage with React

React doesn't remember anything.. localStorage does!

To make the Home component able to restore the last fetched matchday, I can use the localStorage object.

Window.localStorage is a small memory hosted by the clients' browser and it can be used to store some "helpers" values. To learn more about it, take a look at https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage.

Fetching the last fetched matchday

So, in the Home.tsx

constructor(props: IProps) {
  super(props);

  /** localStorage **/
  let matchday;
  if (localStorage.getItem('lastFetchedMatchday')) {
    matchday = Number(localStorage.getItem('lastFetchedMatchday'));
  } else {
    matchday = 1;
    localStorage.setItem('lastFetchedMatchday', matchday.toString());
  }
  /** localStorage **/

  this.state = {
    matchday,
    matches: [],
    competition: null,
    error: false,
    totalMatchdays: 38,
  };
}
Enter fullscreen mode Exit fullscreen mode

The code above, before setting the initial state, checks for a record in the localStorage. This record is a key, value pair with the key equal to lastFetchedMatchday.

At line 7 I used Number(...) because the value I got from localStorage is a string and it needed to be converted into a number (as defined with the interface).

Setting the last fetched matchday

The value I fetch from the localStorage needs to be set somewhere in the application. It makes sense to me setting it when I select a new matchday from the select element.

handleChange = (event: any) => {
  this.setState({ matchday: event.target.value }, () => {
    /** localStorage **/
    localStorage.setItem('lastFetchedMatchday', this.state.matchday.toString());
    /** localStorage **/
    this.fetch();
  });
};
Enter fullscreen mode Exit fullscreen mode

As before, I used this.state.matchday.toString() because localStorage stores strings as I can see from the method definition

Storage.setItem(key: string, value: string): void

Conclusion

At this point, once picked a matchday from the select, I don't lose my last selection even if I reload the page or if I close the browser.

Alt Text

Discussion (0)