I'm practicing React with Redux and in this stage edit or update a nested array. I can't get it to work for me.
State default (array of objects):
[
{
"id": 10,
"title": "president",
"totalParticipants": 0,
"desc": "Selects a new member to represent",
"options": [
{
"id": 1408,
"nameOption": "Kim",
"vote": 0,
"checked": false
},
{
"id": 1527,
"nameOption": "North",
"vote": 0,
"checked": false
}
]
},
{
"id": 11,
"title": "best players",
"totalParticipants": 0,
"desc": "Selects a new best player",
"options": [
{
"id": 150,
"nameOption": "Jhon",
"vote": 0,
"checked": false
},
{
"id": 152,
"nameOption": "Gerald",
"vote": 0,
"checked": false
},
{
"id": 153,
"nameOption": "Sofi",
"vote": 0,
"checked": false
}
]
},
]
I have a function reducer
case 'ADD_VOTE':
const getPoll = action.values.map(poll => poll);
// get index to option
const optionIndex = getPoll.map(dat => (
dat.options.findIndex(opt => opt.id === action.id)
));
// get value to options
// const option = action.vote.map(opt => opt.options[projectIndex]);
const optionVal = action.values.map(poll => (
poll.options[optionIndex]
))
const nextPoll = {
...action.values,
options:[
{ vote: + 1 }
]
};
return {
...state,
nextPoll
}
And function action
export const addVotePoll = ({ id }, values) => ({
type: 'ADD_VOTE',
id,
values,
})
When I throw dispatch event it passes idSelected and data of poll current.
For example: I will select name option "KIM" (state default), then send id (1408) and send data of poll... (idPoll, title, desc, option, etc).
I read something about immutable.js but I haven't tried it yet.
return { ...state, ...nextPoll }would make much more sense, but this will still clearoptions, because you didn't include the old value