1

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.

0

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.