0

hey guys I'm currently trying to use hooks and useContext to do authentication

I defined useContext in this file:

import { createContext } from "react";

export const UserContext = createContext(null);

in my Router file I have setup useContext in this way:

export default function Router() {
  const [user, setUser] = useState(null);
  const value = useMemo(() => ({ user, setUser }), [user, setUser]);

  return (
    <Switch>
      <UserContext.Provider value={value}>
        <Route path="/login" component={Login} />
      ...
      </UserContext.Provider>
    </Switch>
  );
}

Now in my login function I have a problem in my handleSubmit that gets triggered by my form (my backend calls and fetch all work great):

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const { user, setUser } = useContext(UserContext);

  const handleSubmit = async (event) => {
    event.preventDefault();
    const obj = {
      Email: email,
      Password: password,
    };

    loginSession(obj);
    const session = await getUserData();
    setUser(session);
  };

in const session = ... I get my account data When I setUser(session)

I get the following error: login.js:25 Uncaught (in promise) TypeError: setUser is not a function

Can anyone help me? I'm trying to figure this out for some hours I read that hooks shouldn't be used everywhere but I guess a function that handles a Submit is fine right?

I also tried to put the code directly in the onSubmit:

onSubmit={async (event) => {
          event.preventDefault();
          const obj = {
            Email: email,
            Password: password,
          };

          loginSession(obj);
          const session = await getUserData();
          setUser(session);
        }}
   
    Prints the same error

richie4k2k
  • 111
  • 1
  • 1
  • 7
  • just try loggin the context value like `const contextValue = useContext(UserContext);` and loggin it to see what it gives you – amdev Jul 17 '20 at 19:06
  • I dont really understand what you mean with loggin the contextValue should I just log the user? console.log(user); prints out undefined – richie4k2k Jul 17 '20 at 19:08
  • no, i meant that assign the `= useContext(UserContext)` to a variable like `contextValue ` and log it to the console to se what it gives you – amdev Jul 17 '20 at 19:31
  • I get {value: null, setValue: ƒ} – richie4k2k Jul 17 '20 at 20:29
  • so your function is `setValue` instead of `setUser` that you use, but thats interesting!!!! – amdev Jul 18 '20 at 05:22
  • I played around with it yesterday without changing a lot somehow it works now! Currently my problem is just that I cant useContext for global state. In my current page I get the User that I set displayed but when I switch between pages it deletes the user again – richie4k2k Jul 18 '20 at 10:31

0 Answers0