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

294
Vistas
how to call to api once a hour with react

i would like to know how can i get the api on first time reload the page and then call to api again once a hour to update my UI because that api update once a hour by default

here is my code

const [news, setNews] = useState([])

useEffect(() => {
    setInterval(() => {
        (async () => {
            tryÏ {
                const res = await fetch(`https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""`)
                const data = await res.json()
                setNews(data)
                console.log("yes")
            } catch (error) {
                console.log(error)
            }
        })()
    }, 36000000);
}, [])

with that code i can't get result on first time page reload, only after a hour...

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

0

Move your API call to separate function. Call it on page load and on timeout:

let callApi = async () => {
        try {
            const res = await fetch(url)
            const data = await res.json()
            setNews(data)
            } catch (error) {
            console.log(error)
        }
    };

useEffect(() => {
    callApi();

    setInterval(callApi, 1000 * 60 * 60)
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can create another function and call from interval and outside both.

const [news, setNews] = useState([]);

useEffect(() => {
  const fetchData = async () => {
    try {
      const res = await fetch(
        `https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""`
      );
      const data = await res.json();
      setNews(data);
      console.log("yes");
    } catch (error) {
      console.log(error);
    }
  };
  fetchData();
  const interval = setInterval(() => {
    fetchData();
  }, 36000000);

  return () => clearInterval(interval);
}, []);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try this code:

const [news, setNews] = useState([]);
  const [timer, setTimer] = useState(null);

  const APIResponse = async (url) => {
    try {
      const response = await fetch(url);
      const data = await response.json();
      setNews(data);
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    APIResponse("https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""");
    setTimer(
      setInterval(async () => {
        APIResponse("https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""");
      }, 5000)
    );
    return () => clearInterval(timer);
  }, []);
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