Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set state array with nested array values from object

I initialize component state with the store state which pulls api data. I filter the array of data by object name. This then will setState with the object chosen by the user via a button. This works, all objects change without issue. The problem I cannot for the life of me figure out is what I want is to setState onClick with a nested array of objects associated with the category. So each category object has a nested subCategory array which holds many subCategories.

So a generic example would be:

const arr = [
 { name: 'Do', id: 1, sub: [{sub_id: 1, something: 'dog'}, {sub_id: 1, something: 'cat'}] },
 { name: 'Re', id: 2, sub: [{sub_id: 2, something: 'bird'}, {sub_id: 2, something: 'mouse'}] },
 { name: 'Me', id: 3, sub: [{sub_id: 3, something: 'lion'}, {sub_id: 3, something: 'moose'}] }
];
class BrainFart extends Component {
    constructor(props) {
       super(props)
       this.state = { foo: [] }
    }
    handleArray() {
      const stuff = arr.filter(c => c.sub)
      this.setState({foo: stuff})
    }

} 

This will not set state with the nested array of sub... Any thoughts? Thank you

like image 840
Shawn Sheehan Avatar asked Sep 05 '26 02:09

Shawn Sheehan


1 Answers

Update your handleArray function to:

handleArray() {
    const stuff = arr.filter(c => c.sub);

    this.setState({ foo: [...this.state.foo, ...stuff] });
}

Note the change when setting new value for foo property on component state. In this case we create a new array based on the previous and new data (stuff).

Read more on react docs about how to modify component state.


Current problem is setting foo to the output of foo.push(stuff).

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Read more about push

like image 64
Carloluis Avatar answered Sep 07 '26 21:09

Carloluis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!