DEV Community

Discussion on: React useNavigate faster than useContext

Collapse
 
jacobgavin profile image
Jacob Gavin

In you App.js you aren't setting the same auth state as you do in you Login component. It seems that you have missunderstood the concept of context a bit. Or there are some important bits of code missing here. You need to create a "AuthProvider" that stores your context. And you can handle the login and the "check auth cookie" request in that Provider instead of doing it in different parts of the app.

I can't really point you in the right correction based on this. I recommend reading kentcdodds.com/blog/authentication... to get some understanding of how it can be done.

Is your app.get("/login", ...) function only returning what got passed in req.session.user or have you stripped out some logic there?

Also this useEffect needs to have authState.status in its dependency array like this:

  useEffect(() => {
    if (authState.status == true) {
      navigate("/profile");
    }
  }, [authState.status]);
Enter fullscreen mode Exit fullscreen mode

otherwise it will only check that status on initial render. You can read about it here reactjs.org/docs/hooks-reference.h...

Thread Thread
 
mfatihgul profile image
Muhammet Fatih Gul

Yess. I already have an AuthContext.Provider in App.js and I imported it

<div className="App">
      <AuthContext.Provider value={{ authState, setAuthState }}>
        <Router>
          <Header />
          <Routes>
            <Route exact path="/" element={<Mainpage />} />
            <Route exact path="/login" element={<Login />} />
            <Route exact path="/register" element={<Register />} />
            <Route path="/profile" element={<Profile />} />
            <Route path="/courses" />
          </Routes>
        </Router>
      </AuthContext.Provider>
    </div>
Enter fullscreen mode Exit fullscreen mode

app.get is just returning req.session.user. I created it in app.post('/login'). Here it is

app.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;

  db.query("SELECT * FROM users WHERE email = ?;", email, (err, result) => {
    if (err) {
      res.send({ err: err });
    }

    if (result.length > 0) {
      bcrypt.compare(password, result[0].password, (error, response) => {
        if (response) {
          req.session.user = result;
          // console.log("hello: " + req.session.user);
          res.send(result);
        } else {
          res.send({ message: "Wrong username/password combination!" });
        }
      });
    } else {
      res.send({ message: "User doesn't exist" });
    }
  });
});
Enter fullscreen mode Exit fullscreen mode

Thank you for the tips and the sources. I will check immediately