Skip to content

Instantly share code, notes, and snippets.

@patrixr
Created August 17, 2019 03:47
Show Gist options
  • Save patrixr/89a228c86c5ef505051d9d87ed3226e0 to your computer and use it in GitHub Desktop.
Save patrixr/89a228c86c5ef505051d9d87ed3226e0 to your computer and use it in GitHub Desktop.
Redux Mutation Experiment 2
import _ from 'lodash';
export function setProperty(key) {
return (state, action) => ({ [key]: action[key] })
}
export function increment(key) {
return state => ({ [key]: state[key] + 1 });
}
export function decrement(key) {
return state => ({ [key]: state[key] - 1 });
}
export function updateLoading() {
return state => ({ loading: state.requestCount > 0 });
}
/**
* Mutation to set a boolean value
*
* e.g
*
* {
* "SET_FLAG": setBoolean('flag').to(false),
* "SET_LOADING_STATUS": setBoolean('isLoading')
* .eval('numberOfRequests')
* .gt(0)
* }
*
* @export
* @param {*} key
* @returns
*/
export function setBoolValue(key) {
return {
to(val) {
return (state) => ({ [key]: val })
},
eval(otherKey = key) {
return {
eq: (val) => (state) => ({ [key]: state[otherKey] === val }),
gt: (val) => (state) => ({ [key]: state[otherKey] > val }),
gte: (val) => (state) => ({ [key]: state[otherKey] >= val }),
lt: (val) => (state) => ({ [key]: state[otherKey] < val }),
lte: (val) => (state) => ({ [key]: state[otherKey] <= val })
};
}
}
};
/**
* Wraps multiple mutations as one
*
* @export
* @param {*} muts
* @returns
*/
export function combineMutations(...muts) {
return function (state, action) {
return _.reduce(muts, (changes, fn) => {
return {
...changes,
...fn({ ...state, ...changes }, action)
};
}, {});
};
}
// ---- Store State
const initialState = {
users: [],
requestCount: 0,
loading: false
};
// ---- State Mutations
export const START_REQUEST = 'START_REQUEST';
export const END_REQUEST = 'END_REQUEST';
export const SET_USERS = 'SET_USERS';
const mutations = {
[SET_USERS]: setProperty('users'),
[START_REQUEST]: combineMutations(
increment('requestCount'),
setBoolValue('loading').eval('requestCount').gt(0)
),
[END_REQUEST]: combineMutations(
decrement('requestCount'),
setBoolValue('loading').eval('requestCount').gt(0)
)
};
const reducer = function(state = initialState, action) {
const mut = mutations[action.type];
if (!mut) {
return state;
}
return { ...state, ...mut(state, action) };
}
// ---- Initialize
let store = createStore(
reducer,
applyMiddleware(thunk)
);
export default store;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment