microcipcip/cookie-universal

How do I access $cookies in the store?

MarkBird opened this issue · 3 comments

I am trying to convert code that was client-only to use this library, but I cannot get it to work.

Original code was:

export const getters = {
  getCookie() {
    return window.$nuxt.$cookies.get('token')
  }
}

I've tried changing window.$nuxt.$cookies to app.$cookies and this.$cookies but neither of them work, I just get undefined. I saw somewhere else that I might need to get app from context, but context isn't defined either. I'm stumped.

You should have access by this.$cookie. Do you have a good configuration for this on the nuxt.config? You can check process.client if you want to be sure that it is only called on the client-side.

I haven't tried to access a plugin from vuex getters, however your example looks wrong to me. The getters should be connected to the state object of the store, not to a side-effect like a cookie. I would rather access the cookie through an action/mutation and save the cookie value in the state object.

Vuex getters are reactive Vue objects, so you are breaking the reactivity system with that code in your example.

Thanks. I agree this isn't a good way of doing this - in the end I searched the codebase for where this particular store is being used, found it was literally only 1 component, and just changed that component to use this.$cookies.get directly instead of using $store.getters.

I assume the original author wanted to be able to swap this out for some other store method if necessary but I think that was premature - can close this.