Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
setState, add values to a dictionary?

I'm trying to set a json object with setState, that adds a new key value pair with every for loop.

The object will look something like this eventually.

const data = [
  { accuracy: 5, timeTaken: .8 },
  { accuracy: -120, timeTaken: .5 },
  { accuracy: -170, timeTaken: .5 },
  { accuracy: 140, timeTaken: .6},
  { accuracy: 150, timeTaken: .7 },
  { accuracy: 110, timeTaken: .1},
];

The current function looks a bit like this.,

 if (overall !=null) {
    // var percentageCorrect = (100*(LevStein(results[3].question,results[3].answer)/results[3].question.length))
    const [TestData, setTestData] = useState({})
for (var l = 0; l < overall.length; l++) {
  var results = JSON.parse(overall[l].testdetails.result)



    for (var i = 0; i < results.length; i++) {

      // setTestData({...x:(100*(LevStein(results[i].question,results[i].answer)/results[i].question.length)),})
      console.log("accuracy: ",(100*(LevStein(results[i].question,results[i].answer)/results[i].question.length))," timeTaken: ",results[i].timeTaken)   
    
    }
  }

    // JSON.parse(overall[0].testdetails.result);
  }

How do i just add a new value to TestData to replicate the above json object ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The useState hook can't be called conditionally, this breaks the rules of hooks. It needs to be called in the body of the function component.

Since results is an array you can replace or append it to the testData state (*which should be an array, btw). Use a functional state update to shallow copy the previous state, and map the results array to the object values you want.

const [TestData, setTestData] = useState([]);

...
...

if (overall !== null) {
  overall.forEach(({ testdetails }) => {
    const results = JSON.parse(testdetails.result);

    setTestData(data => [
      ...data,
      ...results.map(({ answer, question, timeTaken }) => ({
        accuracy: 100 * (LevStein(question, answer) / question.length),
        timeTaken
      }))
    ]);
  });
}
about 4 years ago · Juan Pablo Isaza Report

0

You can add the object like this:

setTestData([...testData, { new object }])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!