LeCoda
LeCoda

Reputation: 1016

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 ?

Upvotes: 1

Views: 867

Answers (2)

Soroush Salehi 404
Soroush Salehi 404

Reputation: 323

You can add the object like this:

setTestData([...testData, { new object }])

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 202706

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

Upvotes: 1

Related Questions