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.
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);
}
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>
);
}