2

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.

1 Answer 1

3

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);
}, []);
..
Sign up to request clarification or add additional context in comments.

3 Comments

Or, much simpler, use getSlots().then(setSlots) with the original function
Makes sense, thanks for your help. It now keeps looping and performing the fetch x amount of times, how do I stop this? Do I add a simple check in useEffect before I run getSlots?
Ah yes, there was no dependencies-array argument. If you pass it a [] it should work. Added it to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.