简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM