By jamesdeath123


2017-01-31 03:56:09 8 Comments

Inside reducer, given a state object:

var state = {
        "data": [{
            "subset": [{
                "id": 1
            }, {
                "id": 2
            }]
        }, {
            "subset": [{
                "id": 10
            }, {
                "id": 11
            }, {
                "id": 12
            }]
        }]
    }

As you can see, the data is a nested array, with arrays in each of its elements.

Knowning that action.indexToUpdate will be a index for data, I want to update data[action.indexToUpdate].subset to a new array programmatically. For example, if action.indexToUpdate = 0, then data[0] will be updated from

[{"id":1},{"id":2}]

to

[{"id":4},{"id":5}]

In order to do so, I have:

let newSubset = [{"id":4},{"id":5}]
let newState = update(state.data[action.indexToUpdate], {
                subset: {
                    newSubset,
                },
            })

But when I executed this, it returns error:

TypeError: value is undefined

on the update founction.

I have been looking at the react ducomentation here: https://facebook.github.io/react/docs/update.html but I couldn't really figure out how to do it. Please advise!

1 comments

@Shubham Khatri 2017-01-31 04:08:29

Your update will look like

 var obj = {"state" : {
    "data": [{
        "subset": [{
            "id": 1
        }, {
            "id": 2
        }]
    }, {
        "subset": [{
            "id": 10
        }, {
            "id": 11
        }, {
            "id": 12
        }]
    }]
}}
return update(obj, {
  "state" : {
      "data": {
          [action.indexToUpdate]: {
            "subset": {
                 $set: [newSubset]
            }
          }
      }
  }
})

In case there are other fields in subset, but you only wish to the change the fields at specific index containing other keys, you would write

return update(obj, {
  "state" : {
      "data": {
          [action.indexToUpdate]: {
            "subset": {
                [id]: {$merge: newSubset}
            }
          }
      }
  }
})

@jamesdeath123 2017-01-31 04:20:58

I appreciate your help! Sorry I was overly simplified too much my problem. I have updated the question - please take a look!

@Shubham Khatri 2017-01-31 04:27:13

Check the updated answer

Related Questions

Sponsored Content

1 Answered Questions

Can I bind store's state with a component in react-redux?

2 Answered Questions

1 Answered Questions

1 Answered Questions

[SOLVED] How to update nested states in React, should state be immutable?

2 Answered Questions

[SOLVED] How do I update an Immutable array in a React/Redux environment?

2 Answered Questions

How to update multiple nested objects in Redux

1 Answered Questions

[SOLVED] Dynamic key in immutability update helper for array

1 Answered Questions

[SOLVED] Using React's immutable helper with Immutable.js

Sponsored Content