Home > Software design >  how to reset one of data in pinia state?
how to reset one of data in pinia state?

Time:04-27

I have a design in setting page,every one of them hava reset button, now i using pinia to be store library. I kown $reset is reset the whole pinia state,so,how to reset one of data in pinia state?

CodePudding user response:

The typical way I do this:

const defaultState = {
  foo: 'bar'
}

export const useFoo = defineStore('foo', {
  state: () => defaultState,
  actions: {
    reset() {
      Object.assign(this, defaultState);
    }
  }
})

You get the initial state and a reset() action which resets whatever state has to the initial. Obviously, you can pick and choose what you put in defaultState.


If you only want to reset one particular state prop, without touching anything else, just assign the default value to it:

useFoo().foo = 'bar';

If you find it useful, you can also have a generic update, where you can assign multiple values to state in one call:

actions: {
  update(payload) {
    Object.assign(this, payload)
  }
}

Use it like:

useFoo().update({ 
  foo: 'bar',
  // add more props if needed...
});

Last, but not least, lodash's pick can be used to pick and choose what gets reset, from the defaultState values, without having to specify the actual values:

import { pick } from 'lodash-es';

const defaultState = {
  foo: 'bar',
  boo: 'far'
};

export const useFoo = defineStore('foo', {
  state: () => defaultState,
  actions: {
    reset(keys) {
      Object.assign(this, pick(defaultState, keys));
    }
  }
})

use it like:

useFoo().reset(['foo']);

This only resets foo to 'bar', but doesn't touch current value of boo.

To reset both (using the action above):

useFoo().reset(['foo', 'boo']);
  • Related