0

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>
}

1 Answer 1

1

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>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.