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

171
Visualizações
How do I handle an API response with useState to update a state?

I am working on an API response. My aim is to take this API response to update a specified state.

Here the neccessary code snippet from my functional componenet:

const [recordImagesPayload, setRecordImagesPayload] = useState([]);

  useEffect(() => {
    const headers = { 'Content-Type': 'application/json' };
    // const payload = JSON.stringify({ ...createPayload(), recordImage: newImage });

    request(`${url}`, { headers, method: 'GET' })
      .then((response: any) => response.json())
      .then(json => {
        var obj = JSON.parse(json);
        var res: any = [];
        for (var i in obj) {
          res.push(obj[i]);
        }
        setRecordImagesPayload(res);
        console.log(res);
      });
  }, []);

My console.is not showing the res from my last line of code. I am probably doing something wrong with the response but I don't know what to do.

Please help.

Thanks in advance. :)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I assume the request function is using fetch function, in that case you are already parsing the json response using response.json() call, so the resolved value in the next then is not json, so you don't have to use JSON.parse there

Try running this. Here instead of creating a new array and for loop, we can just use Object.values

useEffect(() => {
        const headers = { 'Content-Type': 'application/json' };
        // const payload = JSON.stringify({ ...createPayload(), recordImage: newImage });
    
        request(`${url}`, { headers, method: 'GET' })
          .then((response: any) => response.json())
          .then(result => {
            const res = Object.values(result);
            setRecordImagesPayload(res);
            console.log(res);
          });
      }, []);
about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks @Akhil. I had a minor issue in my code regarding Typescript which was leading to the issue. The type of the result wasn't specified, but beside that, Akhil's answer was very accurate. Many thanks for the quick response and support.

Here is the final code which worked for me:

useEffect(() => {
        const headers = { 'Content-Type': 'application/json' };
        // const payload = JSON.stringify({ ...createPayload(), recordImage: newImage });
    
        request(`${url}`, { headers, method: 'GET' })
          .then((response: any) => response.json())
          .then(result: any => {
            const res = Object.values(result);
            setRecordImagesPayload(res);
            console.log(res);
          });
      }, []);
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