dai-shi / react-hooks-global-state

[NOT MAINTAINED] Simple global state for React with Hooks API without Context API

Home Page:https://www.npmjs.com/package/react-hooks-global-state

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to easily reset state?

flashman2 opened this issue · comments

I didn't found a way to easily reset global state to initial values.

Currently, to reset a state I need to reset each property of global state object. For a big state objects it is not an easy way. Is it possible to reset global state object with single command/function? Below is my code to reset a state.
Note: Strange, but array can be reset with new array only. Reset not works with globalStateInit.teamsCurrentTimeouts. Not sure why.

Example:

const globalStateInit = {
  teamsCurrentScores: {
    home: 0,
    visitor: 0,
  },
  teamsCurrentColors: {
    home: {
      background: 'red',
      text: 'blue',
    },
    visitor: {
      background: 'yellow',
      text: 'green',
    },
  },
  teamsCurrentTimeouts: {
    home: [false, false],
    visitor: [false, false],
  },
  
};

const {setGlobalState, useGlobalState} = createGlobalState(globalStateInit);

export const resetState = () => {
  setGlobalState(
    'teamsCurrentScores',
    () => globalStateInit.teamsCurrentScores,
  );
  setGlobalState(
    'teamsCurrentColors',
    () => globalStateInit.teamsCurrentColors,
  );
  setGlobalState('teamsCurrentTimeouts', prev => ({
    ...prev,
    home: [false, false],
    visitor: [true, false],
  }));
};

It's somewhat intentional to make bulk changes uneasy.
Yes, I think resetting each property is the right solution in this library.

array can be reset with new array only.

It's probably cased by some other code mutates the array, which should be avoided.