Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
useState to update multiple values in react with one change changing the all the remaining

I've a series of data elements which i am using hooks on.

const [a, setA] = useState(true);
const [b, setB] = useState(false);
const [c, setC] = useState(false);
const [d, setD] = useState(false);

i have used a map to loop through all these four and change them on a click using a function changeOnClick. The function basically reverses the current value and sets the value of all other useStates to false. the function looks like(approach A):

const changeOnClick = (x) => {
    switch (x) {
      case "a":
        setA(!a);
        setB(false);
        setC(false);
        setD(false);
        break;
      case "b":
        setB(!b);
        setA(false);
        setC(false);
        setD(false);
        break;
      .
      .


      default:
        break;
    }
  }

i have tried using these 4 values as an useState object(approach B), i.e.

const [all, setAll] = useState({
   a: true, 
   b: false, 
   c: false, 
   d: false
}); 

but i can't work out a way to use the changeOnClick function. It obviously works with approach A, but i want to learn a new way to use / make the code look succinct. Would really appreciate the help.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

One of the ways to update the object using useState() is to recall the prevState (previous State), spread it (... prevState) and change the property you wish in the setter function, like

setAll((prevState) => ({
    ...prevState,
    a : !prevState.a, // or false 
}));

A bit more detailed usage based on your code

const [all, setAll] = useState({
   a: true, 
   b: false, 
   c: false, 
   d: false
}); 


const changeOnClick = (x) => {
    switch (x) {
      case "a": setAll((prevState) => ({
                  ...prevState,
                  a : !prevState.a, // or false 
                 }));
                 break;
      case "b": setAll((prevState) => ({
                  ...prevState,
                  b : !prevState.b, // or false  as you wiss
                 }));
                 break;
      ...
      })
about 4 years ago · Juan Pablo Isaza Relatório

0

If only one of those states is allowed to be true, then perhaps use a single state and record which feature is active. e.g. setState('a') or setState('b').

I think what you want is to use a curried function. Sorry if there's syntax error, typing this live:

<button onClick={updateState('a')}>AAA</button>
<button onClick={updateState('b')}>BBB</button>
<button onClick={updateState('c')}>CCC</button>
<button onClick={updateState('d')}>DDD</button>

const updateState = (whichState) => (event) => {
   console.log('whichState', whichState)
   console.log('event', event)
   // your code here...
}
about 4 years ago · Juan Pablo Isaza Relatório

0

One way I can suggest is to create a dummy object in the handler itself.

const clonedAll = {
        a: false,
        b: false,
        c: false,
        d: false,
    };

After that in the handler as you are passing the value x which is the key itself. Modify the setState with de-structuring the object and adding the value true to the key itself.

setAll({
        ...clonedAll,
        [x]: true,
    });

Also assign a default value to x for default value to be true.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda