Oz Shurki
Oz Shurki

Reputation: 31

TS2322: Type error while im using useContext with a function

Im tyring to pass through Provider value ={ ..} the states and functions that i want react to listen on changes. I have login function that accept userId and token and a logout function that accept nothing. In the AuthContext i made an interface that declare the types that the functions accept but still i get an TS2322 error.

the Error is:

TS2322: Type '{ userId: string | null; token: string | null; isLoggedIn: boolean; login: (token: string, uid: string) => void; logout: () => void; }' is not assignable to type 'Auth'.   Object literal may only specify known properties, and 'login' does not exist in type 'Auth'.

AuthContext.tsx

import {createContext} from "react";

interface Auth{
  userId:string | null;
  token: string | null;
  isLoggedIn: boolean;
  (t:string | null, id:string | null) : void;
  (): void;
}

export const AuthContext = createContext<Auth | null>(null);

App.tsx

import {AuthContext} from "./shared/context/AuthContext";

const App: React.FC = () => {

const [token, setToken] = useState<string | null>(null);
const [userId, setUserId] = useState<string | null>(null);

const login = useCallback((token:string, uid:string) => {
    setToken(token);
    setUserId(uid);
}, []);

const logout = useCallback(() => {
    setToken(null);
    setUserId(null)
}, []);

return (
    <AuthContext.Provider value={{
        userId: userId,
        token: token,
        isLoggedIn: !!token,
        login: login, //  **** TS2322 Error at this line ****
        logout: logout
    }}>
        <div className="App">
            <BrowserRouter forceRefresh={true}>
                <Switch>
                    <Route exact path="/">
                        <Home/>
                    </Route>
                    <Route path="/login">
                        <LoginForm/>
                    </Route>
                    <Route path="/signup">
                        <RegisterForm/>
                    </Route>
                    <Route path="/cart">
                        <Cart/>
                    </Route>
                    <Redirect to="/" from="*"/>
                </Switch>
            </BrowserRouter>
        </div>
    </AuthContext.Provider>
);
}

export default App;

Upvotes: 2

Views: 658

Answers (1)

Chris
Chris

Reputation: 6631

The error message is actually pretty clear. You need to define the login/logout properties specifically on the Auth interface.

interface Auth{
  userId:string | null;
  token: string | null;
  isLoggedIn: boolean;
  login(token:string | null, uid:string | null) : void;
  logout(): void;
}

Upvotes: 0

Related Questions