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

225
Vistas
React API call returns empty response then returns the data

When following this documentation https://reactjs.org/docs/faq-ajax.html I run the code and if i console.log() the items variable in the return statement. I get the following which causes issues because the first response is empty: enter image description here

The code i used is the following:

import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch("http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
     
          setItems(result); 
        },
    // Note: it's important to handle errors here
    // instead of a catch() block so that we don't swallow
    // exceptions from actual bugs in components.
    (error) => {
      setIsLoaded(true);
      setError(error);
    }
  )
  }, [])


  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {console.log(items)}
    </ul>
    );
  }
}

export default App;

Any help would be great.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It's not 'first response is empty' issue. First console.log runs before the async code executes, when async code executes and you change your state, component rerenders and reruns the console.log with newly updated items that are now filled with data fetched from api.

Perhaps you should read a bit more about react component lifecycles :)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use a conditional to run your code only if result is not empty to avoid crashing.

if (result) { 
   //your code
}
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