RareNCool RareNCool - 1 month ago 10
Javascript Question

Error using react-update

My store:

{
people: [
{
id: 12345,
name: Person 1
},
{
id: 54321,
name: Person 2
}
]
}


I'm trying to update the
name
property on Person 1. I'm using
react-addons-update
like this:

update(state, {
people: {
[action.person.id]: {
name: action.person.name
}
}
}


Where
action.person
is an object
{ id: 12345, name: New name }
.

However, I keep getting an error:


Uncaught (in promise) TypeError: Cannot read property 'name' of undefined(…)


This is being thrown in
react-addons-update
's
update
method. Specifically,

for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]); // Error occurs here
}
}


As far as I can tell the problem is that when
nextValue
,
value
and
spec
are all set to
people
,
k
is set to
action.person.id
. And of course that id doesn't exist in the array (it's an array of people).

So my question is, what can I pass in instead of
[action.person.id]
to do this? According to both this and this what I have should be working.

Answer

here you go

update(state, {
    people: {
        $apply: (people) => people.map((person) => {
            if(person.id !== action.person.id) {
                return person;
            }

            return {
                ...person,
                name: action.person.name
            }
        })
    }
}