T
T
TjLink2021-09-09 05:28:24
Vue.js
TjLink, 2021-09-09 05:28:24

How to access localStorage in store, namely state, using Nuxt.js?

I am trying to access localStorage in store, namely state.
I understand that there is no access to browser methods/objects in SSR.
I'm trying to do this:

export const state = () => {
  if (process.client) {
    return {
      isAuth: localStorage.getItem('isAuth')
    }
  }
}


The development console (Vuex) is empty, there is nothing.
And if so:

export const state = () => {
  if (process.client) {
    return {
      isAuth: localStorage.getItem('isAuth')
    }
  } else {
    return {
      isAuth: 'SomeData'
    }
  }
}


Then he sees server work and isAuth = 'SomeData'

How to get access to localStorage?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TjLink, 2021-09-09
@TjLink

I solved this problem in the following way:
In the layout/default where the Nuxt component is located, in the mounted hook I do the dispatch:

setLocalStorage(state) {
    state.isAuth = localStorage.getItem('isAuth')
  },

If you know a better solution, I'd love to hear it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question