Coder Social home page Coder Social logo

Comments (25)

edgecaststudio avatar edgecaststudio commented on August 12, 2024 25

Got the same error in my store. I can not simply use this.$cookies.set() or this.$cookies.get() - any solutions here ?

I switched to next and React 👌

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024 2

I think that you are getting the app from the wrong place, the context is the second argument:

// Change this
 async nuxtServerInit ({ app, commit, dispatch }, { req }) { ... }
// To this
 async nuxtServerInit ({ commit, dispatch }, { req, app }) { ... }

But if you can, try to use cookies in normal store actions, as nuxtServerInit has some weird bug that I haven't been able to fix yet.

from cookie-universal.

edgecaststudio avatar edgecaststudio commented on August 12, 2024 1

@turukawa Hey man. Im in the sam situation. Im using prisma graphql-yoga and Nuxt I need to pass a cookie to client and server for users. Did you figure this out? Do u happen to have a repo? Any help would be greatly appreciated.

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024 1

@Envoy49 using this.$cookies in getters and mutations is an anti-pattern because they should never contain side effects. AFAIK nuxt doesn't expose the context there, for this very reason.

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

Hi @turukawa try changing app with this so this.$cookie.set(etc) , vue conveniently provide the this key with all the plugins installed.

I think the app variable is actually the restructuring done on {commit} but not 100% sure. BTW you can use async await and have a much cleaner code without the "callback hell":

export const actions = {
  getResponse: async ({ commit }, data ) => {
      const response = await axios.post(`http://some.url/some_request`)
      var response_details = {
        response_variable: response.data.variable
      };
      commit("setResponse", response_details );
      this.$cookie.set("cookie", response_details , {
        path: '/',
        maxAge: 60 * 60 * 24 * 7
      });
  }
}

Edit: obs you'd want to add a try {} catch(e) {} to avoid crashing the app if there are errors.

from cookie-universal.

turukawa avatar turukawa commented on August 12, 2024

Hi ... thanks for the swift reply.

The refactoring with async and await is brilliant, thanks. Still getting an "app is not defined" error, though. I tried this.$cookie.set and got "_this.$cookie is undefined".

I can do this.$cookie in a page .vue using a mixin, but this.$cookie fails when called from the store.

from cookie-universal.

turukawa avatar turukawa commented on August 12, 2024

OK... I did a lot of reading and hunting. I've no idea why this works, but ... window.$nuxt.$cookie.set does the job.

Any idea why this works and not anything else?

Thanks ...

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

@turukawa ooops unless you've renamed the plugin, by default is this.$cookies not this.$cookie.

from cookie-universal.

turukawa avatar turukawa commented on August 12, 2024

I had renamed it ... I think I have it working now, some glitches to iron out ... just not sure of what the difference is between window.$nuxt.$cookies, app.$cookies and this.$cookies. The former works. The latter works on user-facing views, and the app version doesn't seem to work at all (i.e. no access to app, even before trying to access anything associated with app).

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

If you are confused about how Nuxt works, sign up on https://cmty.app/nuxt or https://gitter.im/nuxt/nuxt.js and they'll be happy to help. Unfortunately I haven't worked on Nuxt for 4 months so I am a little bit rusty.

window.$nuxt.$cookies will only work in the browser and not during SSR therefore you should avoid accessing it whenever possible.

app.$cookies doesn't work if you don't have the app variable specified. The app variable can be accessed from Middleware and Plugins for sure, in the store I think it may be available only on a very specific action called nuxtServerInit, but better to ask in the forum :)

Having said that, in the store I always use this.$cookies and never app.$cookies.

Edit: my understanding is that app is just an alias for the vue root instance, and in the store you can just access it with this.

from cookie-universal.

turukawa avatar turukawa commented on August 12, 2024

ah, ok, thanks ... steep learning curve. Well, it's working, so I'll close this ...

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

@turukawa Ok, anyway, if you replace:

getResponse: async ({ commit }, data ) => {} 

with:

getResponse: async (obj, data ) => {console.log(obj)}

You can inspect the object and see if the app property is available there or in the prototype, my suspect is that app and this is the same thing in this case. But let me know if you find out because I'd be interested to find out :)

from cookie-universal.

turukawa avatar turukawa commented on August 12, 2024

I'm not seeing either, sorry. Something I must not be doing ... I assume I need a plugin somewhere that injects app into the context? I'm not sure how to do that.

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

If you don't see the app than it's not available because you can probably access it with this.

from cookie-universal.

turukawa avatar turukawa commented on August 12, 2024

And, finally, updated to latest nodejs and suddenly this is available. Note, I had to change the getResponse action to:

async getResponse ({ commit }, data ) {}

That felt way more painful than it needed to be ;)

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

@turukawa I understand now why you couldn't get it to work. You are using an arrow function, I didn't notice it until now. The arrow function hijacks the this scope because it always refer to its current surrounding lexical scope. I'll give you a simple example of what happens using Vue Methods:

var vm = new Vue({
  el: '#example',
  data: {
    name: 'Vue.js'
  },
  methods: {
    // works, this refers to the vue instance therefore you can access the Vue data object.
    greet1: function () {
        console.log(this.name)
    },
    // works, this refers to the vue instance therefore you can access the Vue data object.
    // declaring a method like this is exactly the same as declaring it with a standard 
    // function above, just using the ES6 syntax
    greet2 () {
        console.log(this.name)
    },
    // doesn't work, the arrow function hijacks the `this` context and now is not 
    // referencing the vue instance anymore, it is referencing his lexical scope 
    // which usually is the `window` object.
    greet3: () => {
        console.log(this.name)
    }
  }
})

See the arrow function warning here.

from cookie-universal.

AnnsophieLangenfurth avatar AnnsophieLangenfurth commented on August 12, 2024

Got the same error in my store. I can not simply use this.$cookies.set() or this.$cookies.get() - any solutions here ?

from cookie-universal.

macleash90 avatar macleash90 commented on August 12, 2024

I changed from client side rendering to serverside rendering , after that I could then use app.$cookies or this.$cookies
Here is the change I made to my nuxt.config.js, in export default {}
ssr: true

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

@macleash90 I am about to update the docs regarding what you posted.

from cookie-universal.

macleash90 avatar macleash90 commented on August 12, 2024

@macleash90 I am about to update the docs regarding what you posted.

Thank you for the update, but unfortunately whenever I do use this.cookies.get('token') on the client side I get the error "Cannot read property 'get' of undefined", but on the server side it works fine

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

@macleash90 That may be another issue, I need to see the context where you are using the this.$cookies to see if the context is available there. There are certain places in Nuxt where the context is not available, for example in vuex mutations.

from cookie-universal.

macleash90 avatar macleash90 commented on August 12, 2024

I am using it in a vuex store, located at /store/index.js, here is the code

export const actions = {
    async nuxtServerInit ({ app, commit, dispatch }, { req }) { 
        const token = this.$cookies.get('token')   
        if(token)
        {
            await dispatch('auth/validate')
            .then((resp) => {
                commit('auth/SET_CURRENT_USER', resp)
            })
        }
        else
        {
            commit('auth/SET_CURRENT_USER', null)
        }
    }
  }

When I change to app.$cookies.get('token') I get the error

Cannot read property '$cookies' of undefined

So I switched to this.$cookies.get('token')
In my nuxt.config.js I have ssr: true,
I am new to nuxt, just started using it this week so have not fully understood the concepts

from cookie-universal.

Envoy49 avatar Envoy49 commented on August 12, 2024

I don't understand why this issue is closed?
I can't get access to the context in getters and mutations in VUEX store.
This definitely need to be addressed if anybody has time?

this.$cookies.get(...) this.$cookies.set(...) doesn't do the job.

Only in actions I can use them, but it is not enough

I case somebody needs to set or get cookie in VUEX store I am using this package
https://www.npmjs.com/package/js-cookie

from cookie-universal.

microcipcip avatar microcipcip commented on August 12, 2024

I case somebody needs to set or get cookie in VUEX store I am using this package
https://www.npmjs.com/package/js-cookie

Just a small note, I think that the suggested package by default will not set/get cookies server side, only in client side.

from cookie-universal.

Envoy49 avatar Envoy49 commented on August 12, 2024

I case somebody needs to set or get cookie in VUEX store I am using this package
https://www.npmjs.com/package/js-cookie

Just a small note, I think that the suggested package by default will not set/get cookies server side, only in client side.

Yeap that is correct, In case if anybody needs to get cookies on server side, I don't think that there is any alternative for nuxt-cookie-universal

from cookie-universal.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.