Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading