2

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

3
  • There's no JSON in your question. If the variable with the misleading name json_h would actually contain JSON then Object.entries() would not return the correct values Commented Feb 12, 2022 at 17:19
  • Ok, let me fix the title. It's a simple array. The question is still the same. Commented Feb 12, 2022 at 17:20
  • If it's an array then why do you use Object.entries()? o.O Commented Feb 12, 2022 at 17:20

2 Answers 2

1

You can do:

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

useEffect(() => {
  setSkills([
    ...skills,
    ...Object.entries(json_h).map(([k, v]) => ({[k]: v})),
  ])
}, [json_h])
Sign up to request clarification or add additional context in comments.

1 Comment

That's did the trick. Thanks a lot!
1

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

2 Comments

Excellent!!! I will try that. Thanks!
@user3892548 I've edited the question take a look for more information about the question

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.