unistore icon indicating copy to clipboard operation
unistore copied to clipboard

Page Refresh and Unistore

Open gopalramadugu opened this issue 6 years ago • 3 comments

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

gopalramadugu avatar Mar 08 '19 03:03 gopalramadugu

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

developit avatar Mar 08 '19 12:03 developit

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

Kanaye avatar Mar 09 '19 21:03 Kanaye

@Kanaye I totally forgot! Definitely use unissist - better to save to IndexedDB for sure.

developit avatar Mar 10 '19 20:03 developit