DEV Community

Discussion on: Persisting your React state in 9 lines

Collapse
 
yinonhever profile image
yinonhever

Hey, can I use this code in a class-based component? Or can it only be used in a functional component whose state is managed with Hooks?

Collapse
 
selbekk profile image
selbekk

Hi! Hooks unfortunately require function components to work, but you could recreate the same functionality with either a HOC or just directly in your class component. In your componentDidUpdate, add a line that serializes and saves your state to local storage.

componentDidUpdate() {
  window.localStorage.setItem(
    my state key,
    JSON.stringify(this.state)
  );
}

When you initialize the state, you need to do the reverse:

constructor(props) {
  this.state = JSON.parse(
    window.localStorage.getItem(my state key)
  ) || { fallback: value };
}

Hope that helps!

Collapse
 
ndmax profile image
Nathan Maxwell

Hi @selbekk , thanks so much for your post and this comment reply. When I tried to implement this class-based version, I encountered the following (unfamiliar) error:

Error: Objects are not valid as a React child (found: object with keys {type, key, ref, props, _owner, _store}). If you meant to render a collection of children, use an array instead.

I'm trying to track down this error, but do you have any suggestions to point me in the right direction?

Thread Thread
 
selbekk profile image
selbekk

That happens when you try to render a regular object as children. I’d have to see more of the related code to be of any assistance

Thread Thread
 
ndmax profile image
Nathan Maxwell

Thanks @selbekk , for your reply. That was indeed the case - I was implementing the class-based version in the wrong place within the component hierarchy. The quick fix was simply to locally store only the single piece of state that needed to persist, rather than the entire state object. Works like a charm, and I'm grateful for this post.

Thread Thread
 
jesii profile image
Jon Seidel

Probably need to JSON.stringify that object to store the data in local storage.