Siyahul Haq
Siyahul Haq

Reputation: 469

How to use hooks as value of context provider in react js typescript

I had created a hook that fetches API and I need to call that hook in multiple components but while mounting that component every time the API is re-fetching so I had decided to call that hook as value as React context provider but typescript is not happy when passing value to the provider saying "{ user: { data: any; loading: boolean; error: any; } | { loading: any; data: any; error: any; }; logout: MutationTuple<any, OperationVariables, DefaultContext, ApolloCache>; login: MutationTuple<...>; signup: MutationTuple<...>; }' is not assignable to type 'null"

const AuthContext = React.createContext(null);

export const AuthProvider: React.FC = ({ children }) => {
  return <AuthContext.Provider value={useAuthHook()}> // typescript not happy here
    {children}
  </AuthContext.Provider>
}

Upvotes: 0

Views: 699

Answers (1)

Siyahul Haq
Siyahul Haq

Reputation: 469

pass the return type of hook as type argument while creating context

const AuthContext = React.createContext<ReturnType<typeof useAuthHook> | null>(null);

export const AuthProvider: React.FC = ({ children }) => {
  return <AuthContext.Provider value={useAuthHook()}>
    {children}
  </AuthContext.Provider>
}

and while using that context

export default function useAuth() {
  const context = React.useContext(AuthContext)!;
  if (context === undefined) {
    throw new Error("useAuth must be used within a AuthProvider");
  }
  return context;
}

in a component

export default function MyComponent() {
  const auth = useAuth();
  return (
      <div>Mycomponent</div>
  )
}

Upvotes: 1

Related Questions