Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!