Merge object with React state

Say, I have an object that looks like this:

{
foo: bar,
foo-one: bar-one,
foo-two: bar-two
}

and I have a React state. How can I merge object with state, so object keys will become state keys and object values will become state values apart from standart:

this.setState({
   foo: this.obj.foo,
   foo-one: this.obj.bar-one,
   foo-two: this.obj.bar-two
})

Upvotes: 1

Views: 293

Answers (1)

Gabriel Filipake
Gabriel Filipake

Reputation: 111

You can do that way:

setYourObjectInState = () => {
    const objectWithNewValues = {
        foo: bar,
        foo-one: bar-one,
        foo-two: bar-two
    };

    this.setState({
        ...objectWithNewValues
    )};
}

EXAMPLES OF SET STATE + SPREAD OBJECTS USAGE: Or create an object in your function to reproduce your state and then add the keys with values that you want.

setYourObjectInState = () => {
    const yourObjectInState = {
        ...this.state.yourObjectInState,
        foo: bar,
        foo-one: bar-one,
        foo-two: bar-two
    };

    this.setState({
        yourObjectInState
    )};
}

Or you can simply do like

setYourObjectInState = () => {
    const yourNewObject = {
        foo: bar,
        foo-one: bar-one,
        foo-two: bar-two
    };

    this.setState({
        yourObjectInState: {
            ...this.state.yourObjectInState,
            ...yourNewObject
        }
    )};
}

or even:

setYourObjectInState = () => {
    this.setState({
        yourObjectInState: {
            ...this.state.yourObjectInState,
            foo: bar,
            foo-one: bar-one,
            foo-two: bar-two
        }
    )};
}

Upvotes: 1

Related Questions