I am trying to develop a shopping cart with nuxt js. I am successfully storing the cart data in local storage but I am unable to retrieve the data.
N.B: i don’t wanna use vuex-persistedstate.
Advertisement
Answer
I see lots of small problems with this.
First of all, it looks like you’ve put addToCart
and saveInLocalStorage
judging by the fact you are committing saveInLocalStorage
.
Mutations should only be used to set the state of a single Vuex variable.
They should be pure, meaning they should not have side effects.
You need to use an action for saveInLocalStorage
, and an action to commit
the addToCart
mutation before using dispatch
to run the saveInLocalStorage
action.
Secondly, it’s unclear where you’re actually running this get from local storage function. Are you running it top level of the Vuex store?
If so, to solve the actual problem of it not updating the Vuex store, you will want to have the function responsible for getting the value of storedCart
and using it to set cart
as a mutation to ensure the Vuex store actually updates.
Lastly, there’s no need to use a ternary here. Simply set the Vuex cart
object to be an empty array.