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

Persistence with createGlobalState

aminify opened this issue · comments

Hi, thanks for your amazing work

I was wondering if there is a good way to persist state when using createGlobalState?
I have seen the wiki, but the solution only applies to createStore.

It would be good if we could give a callback to createGlobalState which it calls on every update and we could set the localstorage in there.

There's not a big magic behind the scenes.
If you want to add some features with createGlobalState, you can do at your end.

const initialState = {
  foo: localStorage.getItem('foo') || '',
};

const container = createGlobalState(initialState);

export const setGlobalState = (key, update) => {
  container.setGlobalState(key, update);
  localStorage.setItem(key, container.getGlobalState(key));
};

export const useGlobalState = (key) => [
  container.useGlobalState(key)[0]
  (update) => setGlobalState(key, update)
];

Something like this. Function composition is the way to go.

thank you for your response, that's such a good solution.

can we add this solution to the persistance wiki page so that others can refer to it?

If you confirm this solution works as expected, please go ahead and edit the wiki page.

sure I will test it on my project and update the wiki.
is there a way to get the whole state maybe with getGlobalState in order to store the whole state under a specific persistenceKey rather than shallow keys?

I understand why you ask, but it's intentionally hidden with createGlobaState to avoid overuse it. For the moment, you would need to loop over all keys at your end.

v2 is released and closing this.