beekai-oss / little-state-machine

📠 React custom hook for persist state management
https://lrz5wloklm.csb.app/
MIT License
1.48k stars 53 forks source link

Reset store to initial value ? #129

Closed joe-oli closed 2 years ago

joe-oli commented 2 years ago

I am having a hard time implementing reset store to some initial value; I should ask In stackoverflow, but needs specialized knowledge from people familiar with LSM, hence I am here. This would also help others in understanding LSM better.

the problem

let initValue = {
    siteNumber: ''
    siteName : '',
    phoneContactsArr: [],
    emailContactsArr: []
}
createStore(initValue);

//do stuff... add more props to state, etc.

//later on, I should be able to RESET the store to its initial value (for example, if I am in a steps-wizard, and want to start again).

resetStore(initValue)

workaround

The way I'm doing it now:

export default function clearAction() {
    return {}
}
export default function updateAction(state, payload) {
    return {
        ...state,
        ...payload
    };
}
clearAction()
updateAction(initValue)

** Incidentally, that seems to work, but I got no idea if clearAction is sync, and will finish before updateAction starts !

any suggestions?

Does anybody know how I could write a function

resetStore(initValue)

instead of doing it as per my workaround? (sorry I don't know typescript well enough to know what's going on in the source code of LSM, seems a bit like "magic" to me)

bluebill1049 commented 2 years ago

a simple action to reset the store is all you needed, there will be no specific reset function from this lib.