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

147
Visualizações
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 Respostas
Responde à pergunta

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 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