Skip to content

Instantly share code, notes, and snippets.

@jtulk jtulk/index.js
Last active Jan 11, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.