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

145
Vistas
Async Fetch function not being called in useEffect

I have a simple async function that I want to be called when a page loads which fetches data and updates my context.

import { useContext } from 'react'
import { ContentSlotsContext } from '../commerce-api/contexts'

    export default async function getSlots() {
        const { slots, setSlots } = useContext(ContentSlotsContext)
        const response = await fetch('https://jsonplaceholder.typicode.com/todos');
        const data = await response.json();
        setSlots(data);
    }

I'm trying to call it like this:

useEffect(() => {
    getSlots()
})

slots and setSlots are a setState the context is initialised with.

But it's not being called. When I call it outside of useEffect it works but infinitely loops due to constantly re-rendering.

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

0

The problem is that you're calling useContext from a function that is not a react function component or a custom hook (see the rules of hooks). There's a useful ESLint plugin eslint-plugin-react-hooks that will warn against this.

To fix the issue, you can instead pass setSlots as a parameter to getSlots:

export default async function getSlots(setSlots) {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos');
  const data = await response.json();
  setSlots(data);
}

and call useContext before useEffect, at the top level of your function component (also a rule of hooks), with an empty dependencies array as the second argument, so the effect only fires once (see the note in the useEffect docs):

..
const { setSlots } = useContext(ContentSlotsContext);
useEffect(() => {
  getSlots(setSlots);
}, []);
..
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