0

Code snippet:

updateSelectedAreaColor: (state, payload) => {
state.selectedArea = { ...state.selectedArea, color: payload };
},

I'm updating the property color of the object state.selectedArea with a payload. Instead of hard-coding the property to be updated, I would like to set the property through my payload.
For example:

updateSelectedAreaColor: (state, payload) => {
state.selectedArea = { ...state.selectedArea, payload.target: payload.value };
},

However, this code throws an error. Does anyone know how I can set the value to be updated via the payload?

Jan
  • 188
  • 1
  • 10

1 Answers1

-1

Dynamic properties go into brackets:

 updateSelectedAreaColor: (state, payload) => {
    state.selectedArea = { ...state.selectedArea, [payload.target]: payload.value };
 },

However I would prefer:

 updateSelectedAreaColor: (state, payload) => {
   state.selectedArea = { ...state.selectedArea,  ...payload};
 },

That way, you can easily change multiple props at the same time:

 updateSelectedAreaColor(this.state, { color: "green", backgroundColor: "red" });
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Why mutating the `state` ? – Arup Rakshit Oct 05 '18 at 21:17
  • @arup why not?! – Jonas Wilms Oct 05 '18 at 21:18
  • Because you should not. – Arup Rakshit Oct 05 '18 at 21:19
  • @arup thats the most senseless argument i've ever heard. – Jonas Wilms Oct 05 '18 at 21:20
  • 1
    Sorry, I should have made it clear that I was referring to vuex. I've added the tag. Thank you for your answer! – Jan Oct 05 '18 at 21:42
  • @JonasWilms Why do we tell people in React community don't mutate the state, create a new object? I don't know where it is senseless. You really didn't get my point. Mutation is not really good thing, and it is not related to React. It is true in all programming. – Arup Rakshit Oct 06 '18 at 05:43
  • @arup because when using React, React itself updates the state and causes a rerender, if you mutate the state there, you won't cause a rerender which is why you have to call `setState` to make it work properly. Every stateful framework / whatever has a place where the state gets mutated, however those are well defined. Without knowing the framework that the OP uses it is hard to tell wether mutating `state` is a good thing or not, and I don't give React specific advices if the OP is not using React. – Jonas Wilms Oct 06 '18 at 07:20
  • 1
    @JonasWilms I agree with you. But mutating the object to me felt very wrong. Anyway thanks for taking time to write the answer and comments to clear your thought and my misunderstanding. :) – Arup Rakshit Oct 06 '18 at 16:13