I am trying to update nested data in my reducer. Using the following action, I am returning an array map in my reducer. However my state doesn't change:
case "SUBMIT_ANSWER":
const { current, results, completed } = action.data;
return state.map(video =>
video.id === action.id
? { ...video, current, results, completed }
: video
);
Action:
{
type: "SUBMIT_ANSWER", data: {…}}
data:
completed: false
current: 1
id: 142
results: {correctAnswers: 1, score: 5}
}
Data that needs updating:
{
videos: [{
bookMarked: false
completed: false
correctScore: 5
current: 0
description: "<p>Lorem ipsum dolor sit amet</p>↵"
iconPath: "require('../assets/images/venepuncture.png')"
id: 142
preview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut"
questions: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
results: {score: 0, correctAnswers: 0}
title: "Venepuncture"
totalScore: 50
youtubeVideo: "cxcxcx"
}
......
]}
Assume the following nested state :
{
itemA: 'bla',
name: [
{a: 2, b:3, value:'John', lannguages:['pt','en']}
],
obj:{
obj2:{
nestedArray : [1,2,3]
}
}
}
Now let's assume you want to update the nestedArray
prop uppon an UPDATE_ARRAY
action, passing a number as action.data
to be concat:
switch(action.type){
case 'UPDATE_ARRAY': return{
...state,
obj:{
...state.obj,
obj2:{
...state.obj.obj2,
nestedArray : state.obj.obj.nestedArray.concat(action.data)
}
}
}
}
Just use the spread operator in the right order and you should be fine!