DarkLite1
DarkLite1

Reputation: 14695

What is the best way to clear the properties of an object in Vuex state

Suppose you have this object in the state of the Vuex store:

const state = {
  profile: {
   name: "Bob",
   jobTitle: 'Baker',
   age: 38,
  }
}

In the Vue.js template you can access this object with a computed property like this:

<template>
    <p>Welcome {{ profile.name }}</p>
</template>

This works fine but requires the properties to be defined upfront. And when there is no logged on user each property of profile needs to be set to an empty string. Because when we set state.profile = null the Vue template will complain that it can't find the property name anymore.

What is the best way to handle a case like this? Would we need to iterate the object properties and set them all to a blank string or is there a better way of handling this?

Thank you for your help.

Upvotes: 2

Views: 845

Answers (1)

gvdvenis
gvdvenis

Reputation: 54

You could use a factory method that returns an empty profile object/model to initialize your state. Then you add a reset action to your VUEX store that re-initializes your profile state whenever you need it.

Look at THIS article. This explains the above in more detail.

Upvotes: 1

Related Questions