Home > Software engineering >  How to iterate over array and save data using hooks
How to iterate over array and save data using hooks

Time:02-13

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!!!

CodePudding user response:

Skills are array of objects at first but you change it to single object in the loop that's why you only see the last output in the state

this should fix your problem

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

though I suggest save the new values in a temporary array then change the state once this will get rid of unnecessary setState calls

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

CodePudding user response:

You can do:

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

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