0

I have object={x:[],y:[],z:[]} got from Api and passed it as prop from <Acomponent/> to child <Bcomponent/> like <Acomponent data={object}/>.

<Bcomponent/> state is {a:[],b:[],c:[]} I want data props from <Acomponent> to be added to state of <Bcomponent/>

(i.e) final state of <Bcomponent/> has to be

{a:[],b:[],c:[],x:[],y:[],z:[]}

How it can be done?

Junie
  • 397
  • 2
  • 3
  • 12
  • 1
    Possible duplicate: https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically or https://stackoverflow.com/questions/40601834/deep-merge-of-complex-state-in-react – Janick Fischer Mar 23 '18 at 12:55

3 Answers3

1

Just use constructor

class Bcomponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                a: [],
                b: [],
                c: [],
                x: props.data.x,
                y: props.data.y,
                z: props.data.z
            }
        }
        ...
    }

or setState in componentWillReceiveProps

Andrii Starusiev
  • 7,564
  • 2
  • 28
  • 37
0

You can use the object spread syntax to merge objects:

class Bcomponent extends React.Component {
    constructor(props) {
        super(props);

        const {data} = props;

        this.state = {
            a: [],
            b: [],
            c: [],
            ...data,
        }
    }

    // ...other functions
}
trixn
  • 15,761
  • 2
  • 38
  • 55
0
state = {
 a: [], b: [], c: [], ...this.props.data
};

Demo https://codesandbox.io/s/q30w3q97r9

Dkhili amine
  • 169
  • 5