Home > OS >  Singin is not a function react context
Singin is not a function react context

Time:07-09

I'm trying to build a function that will makes the login context in react using typescript. The IDE says no errors, however, when trying to run the function, it gives me this error Erro ao autenticar: TypeError: singIn is not a function.

Here is my code for the page:

    const { singIn, user } = useAuth();

    async function handleLogin(event: FormEvent){
        event.preventDefault();

        if(!user){
            try {
                await singIn(email, password);
            } catch (err) {
                console.error("Erro ao autenticar: " err)
            }
            
        }
    }

Here is my code for the auth:

type User = {
    email: string;
    name: string;
    password: string;
}

type AuthContextType = {
    user: User | undefined;
    singIn: (email: string, password: string) => Promise<void>;
    singOut: () => Promise<void>
  
}

type AuthProvider = {
    children: ReactNode
}

export const AuthContext = createContext({} as AuthContextType);

export function AuthProvider(props: AuthProvider){
    const [ user, setUser ] = useState<User>();
    const [ emailTry, setEmailTry ] = useState("");
    const { userGet } = useGetUser(emailTry);

    const navigate = useNavigate();

    async function singIn(email: string, password: string) {
        //Code to authenticate
    }

    async function singOut() {
        //Code to Logout
    }

    return(
        <AuthContext.Provider value={{user, singIn, singOut}}>
            {props.children}
        </AuthContext.Provider>
    )
}

Any idea about how to fix this?

CodePudding user response:

Make sure you are involving your App with the AuthContext. See in my code:

import React from "react";
import { Router } from "react-router-dom";

import Routes from "./routes";
import history from "./routes/history";

import { AuthProvider } from "./context";

import Theme from './theme';

import { ThemeProvider } from "@material-ui/core/styles";

function App() {
  return (
    <ThemeProvider theme={Theme}>
      <AuthProvider> {/* here I'm doing that with my AuthProvider */}
        <Router history={history}>
          <Routes />
        </Router>
      </AuthProvider>
    </ThemeProvider>
    
  );
}

export default App;

If you do not do that with the Context, the functions from Context turn into not recognized functions for the other components.

  • Related