Last active
February 16, 2020 10:04
-
-
Save topherPedersen/08fea6d6bb9db2ba070491ea5b02cfe3 to your computer and use it in GitHub Desktop.
Working Redux Reducer
This file contains 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
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