Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Last active February 16, 2020 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topherPedersen/08fea6d6bb9db2ba070491ea5b02cfe3 to your computer and use it in GitHub Desktop.
Save topherPedersen/08fea6d6bb9db2ba070491ea5b02cfe3 to your computer and use it in GitHub Desktop.
Working Redux Reducer
const initialState = {
snacks: []
}
const logCaloriesReducer = (state, action) => {
// check for state undefined to prevent
// redux from crashing app on load
if (typeof state === 'undefined') {
return initialState;
}
switch(action.type) {
case 'LOG_CALORIES':
const newState = JSON.parse(JSON.stringify(state));
const indexOfNextSnack = state.snacks.length;
const newSnack = {
calories: action.payload.calories,
time: action.payload.time
};
newState.snacks[indexOfNextSnack] = newSnack;
return newState;
default:
return state;
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment