Utilizing Object Assign to reset the state

Here lies the declaration of my current state:

export default new Vuex.Store({
  state: {
    items: [
    ],
    user: {
      isAuthenticated: false,
      info: {
        createdAt: '',
        email: '',
        firstName: '',
        id: '',
        lastName: '',
      },
      token: {
        accessToken: '',
        expiresIn: '',
        refreshToken: '',
        tokenType: '',
      },
    },
  },
  actions,
  mutations,
  getters,
  plugins: [createPersistedState({
    key: 'persistedState',
    paths: ['user'],
  })],
  strict: process.env.NODE_ENV !== 'production',
});

I maintain a separate default user state to avoid manual property resets when needed.

export const defaultUser = {
  isAuthenticated: false,
  info: {
    createdAt: '',
    email: '',
    firstName: '',
    id: '',
    lastName: '',
  },
  token: {
    accessToken: '',
    expiresIn: '',
    refreshToken: '',
    tokenType: '',
  },
};

During a logout action:

export const logout = ({ commit, dispatch }) => {
  commit(types.LOGOUT_USER);
  dispatch('changeStatus', 'You need to login or register.');
};



[types.LOGOUT_USER](state) {
  Object.assign(state.user, defaultUser);
},

However, there are moments when the user object doesn't seem to get completely replaced... (or is the default state retaining previous values?)

Answer №1

Aside from what has already been mentioned: This query can be seen as an indirect duplicate of Another question related to similar topic.

Object.assign is considered safe to utilize for up to 2 levels of nesting.

For instance,

Object.assign(myObj.firstProp, myDefaultObj.firstProp);

As stated in the Mozilla Developer Network documentation:

Important Notice Regarding Deep Cloning For deep cloning tasks, it's advisable to explore other alternatives since Object.assign() simply duplicates property values. In cases where a source value points to an object reference, it only replicates that reference value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Could you please ensure that the animation activates upon hovering over the "a" element?

Utilizing bootstrap, I have created the following code. I am looking to add functionality that triggers an animation upon mouseover of an img or a element, and stops the animation upon mouseleave. .progress-bar { animation: pr 2s infinite; } @keyfr ...

Are `<text>` nodes unable to utilize ligature fonts in CSS/SVG?

Check out this JsFiddle demo: http://jsfiddle.net/d0t3yggb/ <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div class="material-icons">add add add add</div> <svg width="100%" height="100% ...

I am encountering a problem with the image source in my Next.js project

I've encountered an issue with using Sanity image URLs in my project. The error message displayed in my console page reads: next-dev.js?3515:25 Warning: Prop src did not match. Server:"https://cdn.sanity.io/images/jbcyg7kh/production/4f6d8f5ae1b ...

Upon reloading, the dynamically generated table does not appear accurately

When a table is dynamically created using JavaScript/jQuery/html from an Ajax call, it initially displays correctly formatted. However, upon refresh/reload, the formatting of the table becomes incorrect. To address this issue, I have implemented a Promise ...

Removing an element from an array by evaluating each item within the array

Input array: ["temp/1/Lounge/empty", "temp/1/Lounge/66,66,66,66,66,66,66,66,64,64,64,64…,64,64,64,64,64,64,64", "temp/2/Lounge/empty", "temp/3/Lounge/empty"] I have a list of elements like the above. Each element consists of four parts separated by s ...

Extract information from a JavaScript function utilizing Python's Selenium

Is there a way to extract data from within a JavaScript function using Selenium? Visit the page here Here is the input code: <script type="text/javascript"> var chartData1 = []; var chartData2 = []; var chartData3 = []; ... ...

Ensure that clicking on various links will result in them opening in a new pop-up window consistently

I am facing an issue with my HTML page where I have Four Links that are supposed to open in separate new windows, each displaying unique content. For instance: Link1 should open in Window 1, Link2 in Window 2, and so on... The problem I'm encounter ...

Upload multiple files using a single input field

Is there a way to upload multiple files using connected input blocks? Additionally, is it possible to store this data in an array of objects? https://i.sstatic.net/eOyrf.png ...

I'm facing a MongooseServerSelectionError: when trying to connect to 127.0.0.1:27017. Despite trying all the solutions provided on StackOverflow, the issue persists

MongooseServerSelectionError: Failed to connect to 127.0.0.1:27017 at NativeConnection.Connection.openUri (/mnt/d/Ecommerce/node_modules/mongoose/lib/connection.js:802:32) at /mnt/d/Ecommerce/node_modules/mongoose/lib/index.js:341:10 at ...

Guide on duplicating text and line breaks in JavaScript

There is some text that looks like this text = 'line 1' + "\r\n"; text+= 'line 2' + "\r\n"; text+= 'line 3' + "\r\n"; I have developed a function to help facilitate copying it to the clipboard ...

Creating Dynamic Input Binding in Vue.js with an Array of Computed Properties

Currently, I am faced with a situation where I need the v-model binding of an input field to be determined by the computed property's returned value. Take a look at the example provided below: <!DOCTYPE html> <html> <head> <scri ...

Issue: In Firefox, resizing elements using position:absolute does not work as expected

My resizable div code looks like this: #box { height: 10rem; width: 10rem; resize: both; overflow: hidden; border: solid black 0.5rem; position: absolute; pointer-events: none; } <div id="item"></div> While it works perfectly ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

Despite providing the correct token with Bearer, Vue 3 is still experiencing authorization issues

I am working on a project that involves Vue 3 with a Node Express back-end server and Firebase integration. On the backend server, I have implemented the following middleware: const getAuthToken = (req, _, next) => { if ( req.headers.authori ...

If viewed on a mobile device, separate the array (indexed list) into two rows

Currently, I am working on my Ionic project where I am trying to implement an indexed list horizontally instead of vertically. While the list looks good as it is now, I want to make sure it supports smaller screen devices too by splitting the list into two ...

Converting a JSONArray object into jQuery format

Within my Java code, there exists a JSONArray object labeled colorList that stores a collection of different colors. For example, the array may be constructed like so: ["Red", "Yellow", "Blue"] I am seeking guidance on how to transfer this information ...

I'm currently working on developing a chat system, but I'm facing an issue where I am unable to send multiple messages consecutively. It seems like there is a problem with the form

My chat application is not allowing me to post multiple messages. Here is the code snippet responsible for sending messages: window.typing = false; var posted = 0; var canPost = 1; var donotrefresh = 0; document.forms['send'].addEventListener(& ...

Easily access all files within a directory without the need to individually list each file for import

Is there a way to import all components from a folder in Vue.js without manually creating an index.js file and individually importing/exporting each component? Here is the folder structure: src/templates/ Foo.vue Bar.vue ...

Utilizing Promise and setTimeout in a generator function to develop an asynchronous generator: A comprehensive guide

I am currently working on creating a generator function that produces an async generator. This Generator will yield a deferred value at each time, using promises. The values and their respective delays (in milliseconds) are sourced from two separate arrays ...

What is the correct way to reuse sub-dependencies using NPM?

This inquiry primarily centers around the usage of react-admin, as indicated by the tags, but could also be applicable in other scenarios. In our case, we are utilizing react-admin which relies on @material-ui/core. This grants us the ability to incorpora ...