Home > Software design >  Changing single value state to object state
Changing single value state to object state

Time:09-25

I have this line to set state.

const [selectedGames, setSelectedGames] = useState('');

However, I want to instead have a state object with multiple properties. e.g. name, date etc. How do I modify that line to allow this and then also how do I set say the name property of the state?

CodePudding user response:

Set an object for your state

const [selectedGames, setSelectedGames] = useState({
  a: 1,
  b: 2,
  c: 3
});

Use spread operator for the keys and update the property you want with

setSelectedGames({...selectedGames, c: 4})

Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.

Read more about Spread syntax

CodePudding user response:

You can create the state like

const [selectedGames,setSelectedGames] = useState({key:value}

create as many key:value as you like.

And to set Any key a value use the setSelectedGames() method like:

 setSelectedGames({...selectedGames,key:newValue})

...selectGames is all The states you don't want to change or to keep as is

  • Related