Last active
February 3, 2019 23:07
-
-
Save js2me/b34525f52d26e04b0fd30abbeabb5083 to your computer and use it in GitHub Desktop.
Reducer helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash' | |
import { createActions as createReduxActions } from 'redux-actions' | |
// That is simple functions (getFromStorage -> (key, fromSession) => window[fromSession ? 'sessionStorage' : 'localStorage'].getItem(key) | |
import { getFromStorage, saveToStorage } from './storage' | |
const convertStringToReduxPath = str => _.upperCase(str).replace(/ /g, '_') | |
export const createReducer = (map, name, modificator) => | |
_.reduce( | |
map, | |
(reducerMap, reducer, key) => { | |
reducerMap[`${name}/${convertStringToReduxPath(key)}`] = modificator | |
? (...args) => modificator(reducer(...args)) | |
: reducer | |
return reducerMap | |
}, | |
{} | |
) | |
export const createActions = (reducerMap, overrideActions = {}) => { | |
let actionsPath = '' | |
const actionsMap = _.reduce( | |
reducerMap, | |
(actionsMap, reducer, key) => { | |
const [actionsName, actionName] = key.split('/') | |
if (!actionsMap[actionsName]) { | |
actionsPath = actionsName | |
actionsMap[actionsName] = {} | |
} | |
actionsMap[actionsName][actionName] = | |
overrideActions[_.camelCase(actionName)] | |
return actionsMap | |
}, | |
{} | |
) | |
const reduxActions = createReduxActions(actionsMap) | |
return reduxActions[_.camelCase(actionsPath)] | |
} | |
export const createCachableState = (stateName, defaultState, saveToSession) => { | |
const key = `${stateName}-state` | |
const modificator = state => | |
state | |
? saveToStorage(key, state, saveToSession) | |
: getFromStorage(key, defaultState, saveToSession) | |
return { initialState: modificator() || defaultState, modificator } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment