I’m using a React context in Typescript to load the user data about the user who’s logged into my app (name, id, email etc.). However, when I use the useContext hook to access that data, which I’m fetching from an API, the data that comes back could be null/undefined if the hook hasn’t completed yet (understandably so). However, if I have other hooks that are dependent on user data (like looking up data with the user id), I don’t want that user data to potentially be undefined. I understand that I could use an isLoading field on the context, but since I will be needing this user data on just about every screen that’s a child of this context provider, I would prefer if none of the context provider’s children be loaded/rendered until the user data finished, so that when I use useContext to access the user data, it must be defined. Is there a way to do this or am I not thinking about contexts in the right way?
Here is an example of the context provider:
import { createContext, useState } from "react";
const UserContext = createContext({});
export const UserProvider = ({ children }) => {
const [user, setUser] = useState({});
setTimeout(() => setUser(<something>, 1000);
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};
export default UserContext;
And here is where I would access the context in a consumer:
const { data } = useUserDataContext()
// typeof data is any[] | undefined
// typeof data should just be any[]
Erik Laucks is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.