Skip to content

Instantly share code, notes, and snippets.

@jtulk
Last active January 11, 2019 03:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtulk/bf5607627e0bce92877e2f40b5c484c3 to your computer and use it in GitHub Desktop.
Save jtulk/bf5607627e0bce92877e2f40b5c484c3 to your computer and use it in GitHub Desktop.
An inefficient reducer pattern for updating an array of objects
const initialState = [
{id: '1', content: {title: 'item 1'}},
{id: '2', content: {title: 'item 2'}},
{id: '3', content: {title: 'item 3'}}
]
const action = {
type: 'update',
id: '2',
payload: { content: {title: 'item 2 updated' }}
}
const reducer = (state = intialState, action = {}) => {
switch(action.type){
case 'update':
const updatedItems = state.map(item => {
if(item.id === action.id){
return { ...item, ...action.payload }
}
return item
})
return updatedItems
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment