Search code examples
javascriptvue.jsvuexvuejs3

I keep getting this error in my console everything i visit this route


    VM28353:1 Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at getUser (auth.js?c7d4:11)
    at wrappedGetter (vuex.esm-browser.js?5502:335)
    at Object.eval [as getUser] (vuex.esm-browser.js?5502:88)
    at Object.get [as getUser] (vuex.esm-browser.js?5502:135)
    at Proxy.getuser (Profile.vue?c66d:98)
    at ReactiveEffect.run (reactivity.esm-bundler.js?a1e9:160)
    at ComputedRefImpl.get value [as value] (reactivity.esm-bundler.js?a1e9:1086)
    at Object.get [as getuser] (runtime-core.esm-bundler.js?5c40:2109)
    at Proxy.render (Profile.vue?c66d:26)

Profile.vue This is the only file that calls the getters

computed: {
       getuser() {
        return this.$store.getters.getUser;
       },
     },

    

Auth.js In the console its state that the error is coming from my getUser getters in my auth module

    const getters = {
       isLoggedIn: (state) => !!state.token,
       getUser: (state) => JSON.parse(state.user),
       getToken: (state) => state.token,
    };

    const mutations = {
      setToken: (state, payload) => {
        state.token = payload;
        localStorage.setItem("auth_token", payload);
      },
      setUser: (state, payload) => {
        state.user = payload;
        localStorage.setItem("user", JSON.stringify(payload));
      },
    };

Solution

  • I guess the state.user is already a object therefore you don't need to use JSON.parse since JSON.parse() converts the input into a string. The toString() method of JavaScript objects by default returns [object Object], resulting in the observed behavior.

    Try removing that such that your code should be

    const getters = {
           isLoggedIn: (state) => !!state.token,
           getUser: (state) => state.user,
           getToken: (state) => state.token,
        };