Skip to content

Instantly share code, notes, and snippets.

@igorjs
Created September 11, 2019 23:18
Show Gist options
  • Save igorjs/b3e48c7ced7db0967806a49f46a5fd4f to your computer and use it in GitHub Desktop.
Save igorjs/b3e48c7ced7db0967806a49f46a5fd4f to your computer and use it in GitHub Desktop.
export function localstorageMeta (key: string, reducer: any): any {
return function(state: any, action: any): any {
let nextState = reducer(state, action);
let storageState = JSON.parse(localStorage.getItem(key));
if (action.type === RESET_STATE || action.type.includes('DELETE')) {
localStorage.removeItem(key);
} else if (!state && storageState || action.type === '@@redux/INIT') {
nextState = storageState;
} else if (nextState && nextState !== storageState) {
localStorage.setItem(key, JSON.stringify(nextState));
}
return nextState;
};
};
// same with cookies
const Cookie = require('js-cookie');
import { RESET_STATE } from './reset';
export function cookieMeta (
key: string,
reducer: any,
expiry: Date | number = 365,
path: string = '/',
domain: string = window.location.hostname): Function {
return function(state: any, action: any): any {
let nextState = reducer(state, action);
let cookieState = Cookie.getJSON(key);
if (action.type === RESET_STATE || action.type.includes('DELETE')) {
Cookie.remove(key);
} else if (!nextState && cookieState || action.type === '@@redux/INIT') {
nextState = cookieState;
} else if (nextState && nextState !== cookieState) {
Cookie.set(key, nextState, { expires: expiry, path: path, domain: domain, secure: process.env.local });
}
return nextState;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment