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

127
Visualizações
loop through a variable and add it to react state variable

I would like to iterate through an array and add the contents to a state variable as an object like so.

var interests = ['jumping', 'singing', 'dancing']   
const [dict, setDict] = useState({}) 

function onClickFunc(interests){
    for (var i=0; i<interests.length; i++){
        setDict({...dict, [interests[i]]: 'checked'})
    }

}

This code would return a dict value of {'dancing' : 'checked}. I want it to return {'jumping' : 'checked, 'singing' : 'checked, 'dancing' : 'checked}. I know this has something to do with setDict() being asynchronous but none of my solutions are working. Please help and Thanks.

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

0

You should just prepare dictionary first, and then set it's value only once.

function onClickFunc(interests){
    const newDict = Object.fromEntries(interests.map(interest => [interest, "checked"])) 
    setDict(newDict);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

export default function App() {
  var interests = ['jumping', 'singing', 'dancing'];
  const [dict, setDict] = React.useState({});

  function onClickFunc(interests) {
    // for (var i = 0; i < interests.length; i++) {
    //   setDict({ ...dict, [interests[i]]: 'checked' });
    // }
    const interestsDict = {};
    interests.forEach((i) => {
      interestsDict[i] = 'checked';
    });

    setDict(interestsDict);
  }
  return (
    <div>
      {console.log(dict)}
      <button onClick={onClickFunc.bind(null, interests)}>Click</button>
    </div>
  );
}
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