Skip to content

Page Refresh and Unistore #143

Open
Open

Description

@gopalramadugu

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

Activity

  1. developit commented on Mar 8, 2019

    @developit
    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) {}
    }
  2. Kanaye commented on Mar 9, 2019

    @Kanaye

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

  3. developit commented on Mar 10, 2019

    @developit
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions