Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the function from the context not recognized?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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>
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading