Search code examples
vue.jsionic-frameworkvuex

Cannot parse JSON from Vuex getter in Ionic Vue


I have an Ionic Project with Vuex. I have created a store:

const store = new Vuex.Store({
state: {
    user: localStorage.getItem('userdata') || {}
},
getters: {
    getUser(state) {
        return state.user
    }
},
mutations: {
    setUser(state, user) {
        state.user = user
    },
    destroyUser(state) {
        state.user = null
    },
},
actions: {
        retrieveUser(context) {
            return new Promise((resolve, reject) => {
                axios.get('v1/user')
                    .then(response => {
                        const user = response.data.data
                        localStorage.setItem('userdata', JSON.stringify(user))
                        context.commit('setUser', user)

                        resolve(user)
                    })
                    .catch(error => {})
            })
        },
}
})

This part works perfect as expected. My localstore holds the JSON string. Now i tried to return the string with the getUser getter JSON.parsed. This doesn't work, because it gives me a parse error which makes no sense, because the string works perfectly fine.

When I try to load the userdata in the vue component like this

export default {
    data() {
        return {
            user: [],
        }
    },
    mounted() {
        this.loadUserData()
    },
    methods: {
        loadUserData() {
            let userData = JSON.parse(this.$store.getters.getUser)
            this.user = userData
        }
    },
}

It returns the JSON Data as Proxy ( ?? )

Proxy {id: 27, name: "English", firstname: "Harriet", fullname: "Harriet English", number: null, …}
[[Handler]]: Object
[[Target]]: Object
[[IsRevoked]]: false

(it's sample data, so no real name shown ) which I cannot use. I have also tried to use the state variable, the localstorage content, which did not work...

How can I access my JSON data?


Solution

  • When you save the user data after your API call, you are storing it in localStorage as JSON.stringify(user) but you are updating the store with just the raw user data. I guess you should update your API call handler to:

    const user = response.data.data;
    const strUser = JSON.stringify(user);
    localStorage.setItem('userdata', strUser);
    context.commit('setUser', strUser);
    

    This should allow you to parse the data the way you are trying to in your component, which should work whether state.user has been initialised with the localStorage data, or if it has been updated after the API call.