Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda