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

Page Refresh and Unistore #143

Open
gopalramadugu opened this issue Mar 8, 2019 · 3 comments
Open

Page Refresh and Unistore #143

gopalramadugu opened this issue Mar 8, 2019 · 3 comments
Labels

Comments

@gopalramadugu
Copy link

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

@developit
Copy link
Owner

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) {}
}

@Kanaye
Copy link

Kanaye commented Mar 9, 2019

There is also a library called unissist that provides persistence for unistore using local storage or indexedDB.

@developit
Copy link
Owner

@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
Labels
Projects
None yet
Development

No branches or pull requests

3 participants