ReactJS with Typescript template useContext property does not exists on type {}

Viewed 177

I created a react-app using yarn create react-app app-name --template typescript, here is my code

AuthProvider.tsx

    import { createContext, useState } from "react";

const AuthContext = createContext({ });
export const AuthProvider = ({ children }: any) => {
  const [auth, setAuth] = useState({});
  
  return (
    <AuthContext.Provider value={{ auth, setAuth }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthContext;

Login.tsx

import React, { useContext, useEffect, useRef, useState } from "react";
import AuthContext from "./context/AuthProvider";
const Login = () => {
  const { setAuth } = useContext(AuthContext);
  /*codes here*/
  return <></>;
};

export default Login;

The error is Property 'setAuth' does not exist on type '{}'.ts(2339), but when I change the file extension to .js it's not showing error. What am I missing here?

1 Answers

You need to define type of AuthContext:

interface Auth {
  // properties of auth object you're using in const [auth, setAuth] = useState({});
};
const AuthContext = createContext<{ auth?: Auth, setAuth?: (auth: Auth) => void }>({ });

Adjust Auth and context type as needed to match your requirements.

Without passing a type to useContext, typescript infers it from the initial value passed to the hook, which is {}, and has none of the properties you're passing to it later in the provider.

Related