DutchPrince
DutchPrince

Reputation: 363

localstorage returning object on reload

i am using vue.js with vuex

In my vuex action i am calling an external api like this:

 //actions.js
 getStudent({ commit }) {
        new Promise((resolve, reject) => {
            student.getStudent()
                .then(response => {
                        localStorage.setItem("userInfo", JSON.stringify(response.data.userData))
                        commit('UPDATE_USER_INFO', JSON.stringify(response.data.userData), { root: true })
                        resolve(response)
                })
        }
 }

In this function userdata is set as a localstorage item. I also call a mutation with commit

when this function is executed for the first time everything works fine with for example this code:

//state.js
const userInfoLocalStorage = JSON.parse(localStorage.getItem("userInfo"))

const setUserRole = () => {
    const userRole = userInfoLocalStorage ? userInfoLocalStorage.role : 'student'
    return userRole
}

const state = {
    Role: setUserRole()
}

Now whenever i reload the page JSON.parse returns the error Unexpected token o in JSON at position 1 and when i remove JSON.parse it returns [object Object]. But when i use JSON.stringify it returns a json object but this works only on first load.

I find it very confusing

Please help me clear out what i should use for best practice.

Upvotes: 0

Views: 800

Answers (1)

Matt U
Matt U

Reputation: 5118

The problem is on this line:

const userRole = userInfoLocalStorage ? JSON.parse(userInfoLocalStorage).role : 'student'

You're calling JSON.parse on an object (userInfoLocalStorage) that has already been deserialized with JSON.parse on the line above:

const userInfoLocalStorage = JSON.parse(localStorage.getItem("userInfo"))

Instead, just do const userRole = userInfoLocalStorage ? userInfoLocalStorage.role : 'student'

Upvotes: 1

Related Questions