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.
CodePudding user response:
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):
..
const { setSlots } = useContext(ContentSlotsContext);
useEffect(() => {
getSlots(setSlots);
});
..