Skip to content

Instantly share code, notes, and snippets.

@third774
Last active February 16, 2019 03:59
Show Gist options
  • Save third774/1e85da424b739f922cc5d0696c9ddd91 to your computer and use it in GitHub Desktop.
Save third774/1e85da424b739f922cc5d0696c9ddd91 to your computer and use it in GitHub Desktop.
// The reducer function looks at each action that comes in
// and based on the type generates a new state based on the
// previous state and any additional data the action carried
const reducer = (state, action) => {
switch (action.type) {
case "COUNT_INCREMENT":
return {
...state,
count: state.count + 1
};
case "COUNT_DECREMENT":
return {
...state,
count: state.count - 1
};
case "COUNT_SET":
return {
...state,
count: action.payload
};
case "NAME_UPDATE":
return {
...state,
name: action.payload
};
default:
return state;
}
};
// Think of actions as an array that gets updated over time.
// Think of the dispatch() api as [].push()
const actionsOverTime = [
{
type: "COUNT_INCREMENT"
},
{
type: "COUNT_DECREMENT"
},
{
type: "COUNT_SET",
payload: 22
},
{
type: "COUNT_DECREMENT"
},
{
type: "NAME_UPDATE",
payload: "k"
},
{
type: "NAME_UPDATE",
payload: "ke"
},
{
type: "NAME_UPDATE",
payload: "kev"
},
{
type: "NAME_UPDATE",
payload: "kevi"
},
{
type: "NAME_UPDATE",
payload: "kevin"
}
];
const defaultState = {
count: 0,
name: ""
}
// Actions are the collection being reduced, and state is the accumulator.
// At any given time, the current state is a "reduction" of the actions
// applied over time using the defaultState as the initial value.
const currentState = actionsOverTime.reduce(reducer, defaultState)
console.log(currentState)
/*
{
"count": 21,
"name": "kevin"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment