Home > other >  Why is the function from the context not recognized?
Why is the function from the context not recognized?

Time:06-17

I'm trying to make an auth Context:

const AuthContext = createContext({});

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

export default AuthContext;

and a custom hook to get it:

import { useContext } from "react";
import AuthContext from "./AuthProvider";

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

export default useAuth;

And now when I try to use the setAuth function:

const Login = () =>{

  const {setAuth} = useAuth();

  ...
  
  setAuth({authResponce});

I get an error : Uncaught TypeError: setAuth is not a function .

I'm new to react and I don't understand the reason yet, so I'll be glad to help.

CodePudding user response:

Context only works if the provider is farther up the component tree than the consumer. If there is no provider, then Login will receive the default value, and you set the default to an empty object when you wrote createContext({});. Since that object has no setAuth function, you get the error.

To fix this, make sure the auth provider is near the top of the tree, and login is inside it. Login doesn't need to be an immediate child of the provider, but it does need to be a descendant.

// Good
const App = () => {
  return (
    <AuthProvider>
      <Login />
    </AuthProvider>
  )
}

// Also good
const App = () => {
  return (
    <AuthProvider>
      <SomeOtherComponent /> 
    </AuthProvider>
  )
}

const SomeOtherComponent = () => {
  return <Login />
}

// Bad
const App = () => {
  return (
    <div>
      <AuthProvider/>
      <Login/>
    </div>
  )
}
  • Related