Last active
January 11, 2019 03:50
-
-
Save jtulk/bf5607627e0bce92877e2f40b5c484c3 to your computer and use it in GitHub Desktop.
An inefficient reducer pattern for updating an array of objects
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 = [ | |
{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