In my Reducer, I'm trying to update the property of an object in an array held within a dictionary collection, but it's not working and I can't figure out why. The results property of my state is a dictionary of key/value pairs, and the value is an array.
I tried to use the map function to create a new array but my results and state does not update. This is my code:
case LOAD_SUCCESS: {
const form = (action as LoadSuccessAction).form;
return {
results: {
...state.results,
...state.results['FORMS'].map(item =>
item.id === form .id
? {...item, 'categories': form.categories}
: item)
},
loading: false,
loaded: true
};
}
What am I doing wrong?
In my Reducer, I'm trying to update the property of an object in an array held within a dictionary collection, but it's not working and I can't figure out why. The results property of my state is a dictionary of key/value pairs, and the value is an array.
I tried to use the map function to create a new array but my results and state does not update. This is my code:
case LOAD_SUCCESS: {
const form = (action as LoadSuccessAction).form;
return {
results: {
...state.results,
...state.results['FORMS'].map(item =>
item.id === form .id
? {...item, 'categories': form.categories}
: item)
},
loading: false,
loaded: true
};
}
What am I doing wrong?
Share Improve this question edited Oct 23, 2018 at 17:46 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked May 16, 2018 at 2:46 james Makindejames Makinde 9933 gold badges18 silver badges37 bronze badges1 Answer
Reset to default 7Here:
...state.results['FORMS'].map(…),
you’re merging the array of updated items (updated FORMS
) with state’s results
property (the object containing FORMS
).
If item’s categories and ids were numbers, the end result would look like this (only showing results
):
{
'0': { categories: 15, id: 10 },
'1': { categories: 7, id: 11 },
FORMS: [ /* its original content before the update */ ],
}
Instead, you should set new state’s FORMS
property to your updated array:
return {
// loaded, loading…
results: {
...state.results,
FORMS: state.results.FORMS.map(
item => item.id === form.id ? {
...item,
categories: form.categories,
} : item,
),
},
}