Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. /**
  2. * Decorator for notesReducer that loads/saves state from local storage
  3. *
  4. * @flow
  5. */
  6. import type { State } from './notesReducer';
  7.  
  8. import { useEffect } from 'react';
  9. import notesReducer from './notesReducer';
  10.  
  11. const LOCAL_STORAGE_KEY = 'appState';
  12.  
  13. function initState() {
  14. console.log('loading');
  15. let loadedState = localStorage.getItem(LOCAL_STORAGE_KEY) || '';
  16. try {
  17. loadedState = JSON.parse(loadedState);
  18. } catch (e) {
  19. loadedState = null;
  20. }
  21. return loadedState || {hash: 0, lastId: 0, notes: []};
  22. }
  23.  
  24. function saveState(state: State) {
  25. console.log('saving: ', state.hash);
  26. localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(state));
  27. }
  28.  
  29. function localStorageReducer() {
  30. const [state, dispatch] = notesReducer(initState);
  31.  
  32. useEffect(() => {
  33. saveState(state);
  34. }, [state]);
  35.  
  36. return [state, dispatch];
  37. }
  38.  
  39. export default localStorageReducer;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement