Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change only one value in a React useState that contains an object and assign a different one to the rest?

I have the following State:

const [clickColumn, setClickColumn] = useState({
    name: 0,
    tasks: 0,
    partner: 0,
    riskFactor: 0,
    legalForm: 0,
    foundationYear: 0
  })

And now, for example, I only want to set name to 2 and the rest to 1. But I do not want to write it this way: setClickColumn({ name: 2, tasks: 1, riskFactor: 1, partner: 1, legalForm: 1, foundationYear: 1 });

How can I make it shorter?

like image 532
avydesign Avatar asked Sep 17 '25 14:09

avydesign


2 Answers

You can use spread operator to make it simple:

setClickColumn({ ...clickColumn, name: 2 });

it spreads the existing object clickColumn and adds the name: 2 to it, overriding the default value. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

like image 139
szczocik Avatar answered Sep 20 '25 04:09

szczocik


Making it shorter wouldn't necessarily make it more simple, but you can do something like this:

const obj = {
  name: 0,
  tasks: 0,
  partner: 0,
  riskFactor: 0,
  legalForm: 0,
  foundationYear: 0
};

const entries = Object.entries(obj).map(([key, value]) => key === 'name' ? [key, 2] : [key, 1]);
const result = Object.fromEntries(entries);
console.log(result);
like image 41
MorKadosh Avatar answered Sep 20 '25 05:09

MorKadosh