Reputation: 107
Hi there i've two question about redux that i want to ask
how do i update a object which is nest in an array inside an object, example would be like this
newInStockList:{
newEntry:[
0:{
id:"584f9b926f69ee93d4eb320d",
name:"apple",
amount:"10"
},
1:{
id:"584f9b926f69ee93d4eb31e5",
name:"orange",
amount:"20" <-------- target
},
]
}
the target that i would want to update is the amount of orange there for i've create a reducer for it, the reducer include few more action as well
export var newInStockList = (state = {newEntry:[]}, action)=>{
switch (action.type){
case 'INSERT_NEW_ITEM_TO_INSTOCK_LIST':
return {
newEntry:[...state.newEntry, action.item]
};
case 'REMOVE_ITEM_FROM_INSTOCK_LIST':
return {
newEntry:[
...state.newEntry.slice(0, action.targetItemIndex),
...state.newEntry.slice(action.targetItemIndex + 1)
]
}
case 'EDIT_ITEM_FROM_INSTOCK_LIST':
return {
newEntry:[
...state.newEntry,
state.newEntry[action.targetItemIndex]:{ <----problem
amount:action.amount <----problem
} <----problem
]
}
default:
return state;
}
}
if i would want to update the amount of orange from 20 to become 30 what am I doing wrong in this reducer? because the output of my reducer would just duplicate a same item (which is orange) once more to the array. What is the key concept that i'm missing that would lead to this mistake?
Second questions is the in the state of the reducer, is newEntry object necessary if there are only one item inside newInStockList? if it is not necessary how could I remove it and how does it affect the rest of my code? i've try to remove all the newEntry with brackets but it gives error on the action.item
Many thanks for the help :D
Upvotes: 2
Views: 10550
Reputation: 107
after doing some more research I realized How to update single value inside specific array item in redux thread got a similar problem as mine the by using immutability help (https://facebook.github.io/react/docs/update.html)
Code update :
import update from 'react-addons-update';
export var newInStockList = (state = {newEntry:[]}, action)=>{
switch (action.type){
case 'INSERT_NEW_ITEM_TO_INSTOCK_LIST':
return {
newEntry:[...state.newEntry, action.item]
};
case 'REMOVE_ITEM_FROM_INSTOCK_LIST':
return {
newEntry:[
...state.newEntry.slice(0, action.targetItemIndex),
...state.newEntry.slice(action.targetItemIndex + 1)
]
}
case 'EDIT_ITEM_FROM_INSTOCK_LIST':
return update(state,{
newEntry:{
[action.targetItemIndex]:{
amount:{$set : action.amount}
}
}
})
default:
return state;
}
}
Upvotes: 6