Search code examples
javascriptarraysreact-hooksuse-effectuse-state

How to iterate over array and save data using hooks


Tha idea is iterate over a array and save (or update) values.

const [skills, setSkills] = useState([]);

useEffect(() => {
    Object.entries(array).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills({ ...skills, [k]: v })
    });
}, [array]);

The output is:

The skill is:  1  and value:  30
The skill is:  2  and value:  40
The skill is:  3  and value:  90

That's ok and I assume that "skills" should be:

{1: 30, 2: 40, 3: 90}
   1: 30
   2: 40
   3: 90

but actually, it only saving the last input. I mean, I see the following:

{3: 90}
   3: 90

Please, somebody can explain why? And how to do it the right way? Thanks!!!


Solution

  • You can do:

    const [skills, setSkills] = useState([])
    
    useEffect(() => {
      setSkills([
        ...skills,
        ...Object.entries(json_h).map(([k, v]) => ({[k]: v})),
      ])
    }, [json_h])