I’m trying to create a context whose default value will come from an external source. I would need to do something similar to doing the fetch outside of an asynchronous function (I don’t think this is possible). The question is: how to perform fetch in this scenario?
import React, { createContext, useState } from "react";
import { Usuario } from "../typings/types";
interface UsuariosContextType {
usuarios: Usuario[]
setUsuario?: React.Dispatch<React.SetStateAction<Usuario[]>>;
}
// I have no ideia how to do it the right way
const usuarios_data = await fetch(`http://localhost:8080/usuarios`, { cache: 'no-store' })
const usuarios_array = await usuarios_data.json()
const usuarios_lista: Usuario[] = usuarios_array
export const UsuariosContext = createContext<UsuariosContextType>({ usuarios: usuarios_lista })
export const UsuariosProvider = (children: React.ReactNode) => {
const [usuarios, setUsuario] = useState<Usuario[]>([])
return (
<UsuariosContext.Provider value={{ usuarios, setUsuario }}>
{children}
</UsuariosContext.Provider >
)
}
2
Answers
To asynchronously load data and set it as a context value, you will need to use
useEffect
to load your data and auseState
to control loading state (which you might use later to display a spinner).In the snippet below, we make an API call in
useEffect
once the context component mounts. In theuseEffect
, we also setisLoading
totrue
. Once the request is finished and parsed, we usefinally
to setisLoading
tofalse
.In React, data fetching must be done inside an asynchronous function, which is not possible outside the component’s lifecycle methods. When initializing a context with external data, the fetch operation should be performed after the component mounts. To handle this, React provides hooks like
useEffect()
that allow you to run side effects (like fetching data) when the component is rendered.I would recommend familiarizing yourself with the async nature of React and effects handling via useEffect() hook.
useState()
hook to store the fetched data.useEffect()
executes the fetch call and saves data into a state, thatwill be represented withing your defined context.
Complete Solution