Home > front end >  TS Errors when declaring types on useContext Provider
TS Errors when declaring types on useContext Provider

Time:10-11

I am having difficulty satisfying TS when setting up a useContext state provider

Here I define the interface

interface UserProvider {
  user: UserWithDetails | null
  setUser: React.Dispatch<React.SetStateAction<UserWithDetails>> | null
}
export const UserContext = createContext<UserProvider | {}>({})

Here I pass my values:

<UserContext.Provider value={{ user, setUser }}>

When trying to access my user in a component I receive the TS Error:

Property 'user' does not exist on type '{} | UserProvider'.

const { user } = useContext(UserContext) // Property 'user' does not exist on type '{} | UserProvider'.

How can I resolve this?

CodePudding user response:

Since your Context's type is UserProvider | {}, you can't be sure that user always exists when you use the context. One way to handle this is to use null instead and do a null check.

interface UserProvider {
  // your user provider
}
const UserContext = createContext<UserProvider | null>(null)

export const useUser = () => {
  const context = useContext(UserContext);

  // At this point, you don't know if your context is null or UserProvider

  if (context === null) {
    throw new Error("UserContext not provided");
  }

  // At this point, you know that your context has to be UserProvider

  return context;
};

Now, in your consumer, you can just consume the useUser hook instead of using the UserContext directly. This helps you to avoid null checks in your component.

// const { user } = useContext(UserContext)
const { user } = useUser()
  • Related