Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persistence with createGlobalState #58

Closed
aminify opened this issue Mar 22, 2021 · 6 comments
Closed

Persistence with createGlobalState #58

aminify opened this issue Mar 22, 2021 · 6 comments

Comments

@aminify
Copy link

aminify commented Mar 22, 2021

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.

@dai-shi
Copy link
Owner

dai-shi commented Mar 22, 2021

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.

@aminify
Copy link
Author

aminify commented Mar 25, 2021

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?

@dai-shi
Copy link
Owner

dai-shi commented Mar 25, 2021

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

@aminify
Copy link
Author

aminify commented Mar 26, 2021

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?

@dai-shi
Copy link
Owner

dai-shi commented Mar 26, 2021

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.

@dai-shi
Copy link
Owner

dai-shi commented Aug 5, 2022

v2 is released and closing this.

@dai-shi dai-shi closed this as completed Aug 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants