persisted.store.cookies.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * A simple implementation to save the actual Redux state into
  3. * a browser cookie so it is sent to the server when the site is loaded.
  4. * The server will read that cookie information an use it as the
  5. * initial state, this way we can render the layout on the server and
  6. * send the classes and themes already applied directly to the client.
  7. */
  8. const REDUX_STORAGE_KEY = 'angle-next-redux-key';
  9. const saveCookie = (cname, cvalue, exdays) => {
  10. let d = new Date();
  11. d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  12. let expires = 'expires=' + d.toUTCString();
  13. document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
  14. };
  15. const readCookie = (cookies, name) => {
  16. const cstr = RegExp('' + name + '[^;]+').exec(cookies);
  17. return decodeURIComponent(!!cstr ? cstr.toString().replace(/^[^=]+./, '') : '');
  18. };
  19. /* Server: Read the saved state from cookies sent from browser */
  20. export const readState = cookie => {
  21. let state;
  22. try {
  23. state = JSON.parse(readCookie(cookie, REDUX_STORAGE_KEY));
  24. } catch {
  25. state = {};
  26. }
  27. return state;
  28. };
  29. /* Client: Export a method to save state on each store update */
  30. export const saveState = state => {
  31. try {
  32. let stateFilter = JSON.parse(JSON.stringify(state)); // deep clone
  33. ['offsidebarOpen', 'asideToggled', 'horizontal'] // states which we don't want to persist.
  34. .forEach(item => delete stateFilter.settings[item]);
  35. const rawState = JSON.stringify(stateFilter);
  36. saveCookie(REDUX_STORAGE_KEY, rawState, 100);
  37. } catch (err) {
  38. console.log(err);
  39. // Ignore write errors.
  40. }
  41. };