Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda