1

I have the following state in a React.Component class:

this.state = {
  stuff: {
    stuffData: [],
    loading: true,
  },
  moreStuff: {
  ...
  }
}

Inside a function, after a button click I want to update the state of stuff to loading.

It works if I do it the following way:

const { stuff } = this.state;
const newStuff = stuff;
newStuff.loading = true;
this.setState({ stuff: newStuff };

But I wanted to do it like this (don't get expected result):

const { stuff } = this.state;
this.setState({ stuff: {loading: true, ...stuff } });

What am I missing?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
zediogoviana
  • 305
  • 3
  • 14
  • 1
    You are overriding the value of loading by using spread operator. I also think, first approach is pretty fine – haMzox Nov 25 '19 at 19:15
  • 1
    You've done it the other way round. Should be `{ ...stuff, loading: true }`, which is the same as `Object.assign(stuff, { loading: true })`. `stuff` is the base object and you are overwriting the loading variable. – dw_ Nov 25 '19 at 19:17
  • 1
    @Santa'sLittleHelper it's not the same since `Object.assign` will mutate `stuff`, while spreading won't mutate `stuff`. – Emile Bergeron Nov 25 '19 at 19:19
  • @EmileBergeron You are correct. My mistake. – dw_ Nov 25 '19 at 19:37

1 Answers1

4

You first copy your object and then change the value you want to change.

const { stuff } = this.state;
this.setState({ 
   stuff: {
       ...stuff, 
       loading: true 
   } 
});

Because if rest = {a:2, b:3}

  • {a: 1, ...rest} will give you {a:2, b:3}

  • {...rest, a: 1} will give you {a:1, b:3}

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Prasanna
  • 4,125
  • 18
  • 41