Home > Mobile >  React Hooks with Typescript - Property does not exist on type
React Hooks with Typescript - Property does not exist on type

Time:01-07

I've got the following provider/context...


interface Props {
  children: JSX.Element
}

const AuthContext = createContext({});

export const AuthProvider = ({ children }: Props) => {
  const [auth, setAuth] = useState({});

  return (
    <AuthContext.Provider value={{auth, setAuth}}>
      {children}
    </AuthContext.Provider>
  );
}

export default AuthContext;

I'm using a custom hook to wrap this context usage like so:

import AuthContext from "../context/AuthProvider";

const useAuth = () => {
  return useContext(AuthContext);
}

export default useAuth;

Then, I am trying to use the hook:

const { setAuth } = useAuth();

And I get an error on setAuth - Property setAuth does not exist on type {}.

This was some code I wrote in es6 that I am converting to TS but I am unsure how to resolve this particular issue.

CodePudding user response:

You should add a generic parameter to your createContext function:

import { useState, createContext, Dispatch, SetStateAction } from 'react';

interface Auth {
  // The properties you expect on the `auth` variable
}

interface AuthContextInterface {
  auth: Auth
  setAuth: Dispatch<SetStateAction<Auth>>
}

With TypeScript, you're also expected to provide an initial value that matches the AuthContextInterface type, which can either be a set of default values or just undefined! to tell TypeScript you're sure that you'll override it later:

const AuthContext = createContext<AuthContextInterface>({
  auth: { /* an initial value for auth */ },
  setAuth: () => {}
});

CodePudding user response:

To fix this issue, you can provide an appropriate default value to the createContext function that includes both an auth object and a setAuth function. For example:

const AuthContext = createContext({
  auth: {},
  setAuth: (auth: any) => {}
});

This should allow you to destructure the setAuth function from the value returned by the useAuth hook without getting an error.

Blockquote

CodePudding user response:

As sometimes I don't have the initial value of the context, I'd suggest:

interface IAuthContext {
  auth: IAuth // Whatever you need to add here
  setAuth: (auth: IAuth) => void
}
const AuthContext = createContext<IAuthContext | null>(null);

  • Related