[Question] Resetting state
iamursky opened this issue · 4 comments
What is the best (the easiest) way to reset a part of the state?
For example:
{
a: {
b: 123,
c: derived(...)
},
d: { ... }
}
How do I reset "a" to its initial state?
I've been wanting to write a method for this feature for a while now.
For now how I handle this is to create a reset action. This works okay for my application because I will typically reset the ENTIRE state object. But you could customize it by passing in params to your action.
For example in my user/state.ts:
type State = {
userid: string;
fullname: string;
isLoggedIn: boolean;
}
export const state: State = {
userid: '',
fullname: '',
isLoggedIn: false
}
then in my user/actions.ts:
export const resetUserState: Action<void, void> = ({state}) => {
state.user = {
userid: '',
fullname: '',
isLoggedIn: false
}
}
to customize it you might pass in an array of keys that you want to be reset.
// If array is empty, reset entire state object
export const resetUserState: Action<string[], void> = ({state}, keys = []) => {
const originalState = {
userid: '',
fullname: '',
isLoggedIn: false
};
if (!keys.length) {
state.user = originalState;
return;
}
for (let key in keys) {
if (state.user.hasOwnProperty(key) {
state.user[key] = originalState[key];
}
}
}
and obviously you'd want to define a type for the array of keys so you wouldn't have to worry about undefined.
Specifically targeting nested objects will be tricky and you'd have to be clever. There definitely should be a built-in method for this, but probably most peoples' state object is not that large and creating separate resetters for each nested object works for most.
@christianalfoni requesting issue closed