C
C
ckatala2020-01-31 09:54:44
React
ckatala, 2020-01-31 09:54:44

How to store state in localstorage ssr await/async?

Tell me how to save the state in localstorage srr
I have a block that is open by default. If you hide it, then when you refresh the page, it opens and then immediately disappears! How can I prevent it from opening on page refresh?

state = {
    closed: false
  }

componentDidMount() {
    if (localStorage.getItem('state')) {
      this.setState({ ...JSON.parse(localStorage.getItem('state')) })
    }
  }

componentDidUpdate() {
    if (this.state.closed === true) {
      document.body.classList.add('block-closed')
    } else {
      document.body.classList.remove('block-closed')
    }
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2020-01-31
@ckatala

localStorage is synchronous. Why not use the value from it when initializing the state?

componentDidUpdate() {
    if (this.state.closed === true) {
      document.body.classList.add('block-closed')
    } else {
      document.body.classList.remove('block-closed')
    }
  }

This is how you shouldn't do it. This is how it should be done.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question