-
Notifications
You must be signed in to change notification settings - Fork 138
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
Page Refresh and Unistore #143
Labels
Comments
import createStore from 'unistore';
// The top-level state properties you want to persist
const KEYS_TO_SAVE = ['foo', 'bar', 'baz'];
const store = createStore(loadState() || INITIAL_STATE);
// throttle saving
let timer;
store.subscribe(() => {
if (timer) return;
timer = setTimeout(saveState, 100);
});
function saveState() {
timer = null;
let state = store.getState();
let saved = {};
for (const key of KEYS_TO_SAVE) saved[key] = state[key];
localStorage.setItem('state', JSON.stringify(saved));
}
function loadState() {
try {
return JSON.parse(localStorage.getItem('state'));
} catch (e) {}
} |
There is also a library called unissist that provides persistence for unistore using local storage or indexedDB. |
@Kanaye I totally forgot! Definitely use unissist - better to save to IndexedDB for sure. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I refresh the page the state is lost with unistore which is similar to redux. React/Redux has middleware libs to persist the state. What are the options with unistore ? I found an interesting article on stackoverflow that talks about saving state to local storage. But things can get messy and the article also mentions about performance issues with frequent state changes.
https://stackoverflow.com/questions/37195590/how-can-i-persist-redux-state-tree-on-refresh
The text was updated successfully, but these errors were encountered: