1

In my react redux reducer, how do I add or update a deep nested array of objects with the spread operator? I’m having trouble getting the syntax right.

My state is roughly in this shape:

state: {
    fields...
    ups: {
        fields...
        ftr: {
            fields...
            arts: [
                {   
                    artId: 12,
                    name: ‘joe’,
                    phones: [
                        {   
                            phoneId: 58,
                            number: ‘nnn’
                        }
                    ]
                }
            ]
        }
    }
}

I come in with artId and either with an empty phone object or an existing one to add/update the phones array. Likewise the same for the parent arts. Can't do byId and too late to switch to 'normilizr`.

1 Answers1

0

To start, it's a little difficult comprehending the exact issue you are having.. It would be extremely useful if you could supply some of the code you are using to update your state inside of your reducer, not just the shape of your state.. In order to accurately assist, we need to see more code..

With that being said, if I am understanding this correctly, when you are updating state in a reducer, you need to make a deep copy first.. or are you trying to use the spread operator like this: fields...?...or is that just for brevity?

The spread operator offers a shallow copy, so you'll have to do something like this to get a deep[er] copy:

case types.SOME_CONSTANT: {
  let _newstate = JSON.parse(JSON.stringify(state));
  _newstate.some.deep.nested.property = action.payload;
  return _newstate;
}
Matt Oestreich
  • 8,219
  • 3
  • 16
  • 41
  • Done!! Thank you so much @Matt-Oestreich! Never occurred to me to use JSON.parse/stringify. I used the [...] operator and Object.assign in all shapes and forms to no avail. Thanks – Saeid Irvani Sep 15 '19 at 00:04
  • No worries! `Object.assign` also offers a shallow copy.. Cloning/copying objects can get real tricky depending on the type of objects you are nesting.. There are many caveats/random things that can go wrong (even when using `JSON.parse`) - you should look into issues with JSON.parse as well as issues with Object.assign... The more you know, the better! Cheers!! – Matt Oestreich Sep 15 '19 at 00:09
  • @SaeidIrvani this is a good read on cloning objects https://stackoverflow.com/a/122704/10431732 figured it would be helpful for you. – Matt Oestreich Sep 15 '19 at 15:15
  • Thank you @MattOestreich for going the extra mile and pointing out the SO thread. I thought about the possible inefficiency of parse/stringify but for now since it's a small object and not too deep, I'm gonna consider it adequate. Plus once I figure out how to use, say `phones[0]` as the top level `state` in my `phone component`, it won't matter anyway since I'll be updating its fields directly. I might even look at `lodash`. Thanks again – Saeid Irvani Sep 15 '19 at 23:57