Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

You can add the object like this:

setTestData([...testData, { new object }])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda