1

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
})
3
  • What's wrong with setState()? What are you trying to do? Commented Mar 11, 2021 at 14:44
  • @Thomas setState is fine. Thing is, my object is quite large. I wanted to know whether I can write less code without making setState big, as I have about 20 keys in my object Commented Mar 11, 2021 at 14:46
  • You know that you only have to set the keys that you actually want to change (in class components). You don't have to pass in the entire state every time. Commented Mar 11, 2021 at 14:49

1 Answer 1

1

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
        }
    )};
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why are you doing setStates job? What's wrong with OPs code? It will automatically (flat) merge the current state with the changes passed in. So why do you manually merge the changes with the previous state? And what's the benefit of this extra object?
I just created an example object to explain, he doesn`t need to create a new one, i will edit with the optional setState creation without a new object (just for readability).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.