1

I have this particular jwt.sign function

Backend

const token = jwt.sign({_id: user._id}, process.env.TOKEN_SECRET, {expiresIn: "1m"})
    res.header('auth-token', token).json(token)

And this is the JS in my frontend that calls the backend on Login attempt.

Frontend

import axios from "axios";

const login = (email, password) => {
    return axios
        .post("http://localhost:4000/auth/login", {
            email,
            password
        })
        .then((response) => {
            if (response.data.accessToken){
                localStorage.setItem("user", JSON.stringify(response.data))
            }
            console.log(response.data)
            return response.data
        })
}

When i succesfully login, i can see that it gives me the TOKEN (with console.log), but when i return in my Homepage i still have the signup / login buttons instead of the logout button

function App() {
  const [currentUser, setCurrentUser] = useState(undefined)

  useEffect(() => {
    const user = AuthService.getCurrentUser()

    if(user) {
      setCurrentUser(user)
    }else{
      console.log("user non ce l'ho")
    }
  }, [])

  const logOut = () => {
    AuthService.logout()
}

  return (
    //previous code
   ----------------------
    {currentUser? (
          <div className='navbar-nav ms-auto'>
            <li className="nav-item">
              <a href="/login" className="nav-link" onClick={logOut}>
                Logout
              </a>
            </li>
          </div>
        ) : (
          <div className="navbar-nav ms-auto">
          <li className="nav-item">
            <Link to={"/login"} className="nav-link">
              Login
            </Link>
          </li>
-----------------------
   //post code
)

I have doubts on this jwt.sign({_id: user._id} , what is _id: user._id

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Bigbool98
  • 82
  • 8
  • The `login` function only sets a value into localStorage. React doesn't watch localStorage, so you will need to add some state to your app that is updated when a user logs in in order to trigger React to rerender and see the updated state value. Are you indirectly asking about how to [create protected routes and handle authentication flow](https://stackoverflow.com/questions/66289122/how-to-create-a-protected-route)? – Drew Reese Jan 16 '23 at 18:24
  • @RyanWilson Probably better the other way around, the `currentUser` moved to a global state and the `login` function accesses the global state to enqueue an update. Effectively an application/implementation of the [Lifting State Up](https://reactjs.org/docs/lifting-state-up.html) pattern. – Drew Reese Jan 16 '23 at 18:34
  • @DrewReese I am somewhat new to `React` and have been trying to learn best practices, etc., isn't passing state from parent/ancestor to children as props the way to go in React? At least that is what is explained here: [passing-state-of-parent-to-child-component-as-props](https://www.pluralsight.com/guides/passing-state-of-parent-to-child-component-as-props) "Passing state as props from parent to child components is a core concept of React." While I suppose the login is not a child component. But wouldn't the Application state be pretty much the top of the heirarchy? – Ryan Wilson Jan 16 '23 at 18:37
  • @RyanWilson Passing props *is* a React basic, but taken to a basic "extreme" introduces an issue called "props drilling" where props are *unnecessarily* passed from ancestor to descendent components via any number of intermediate components that don't necessarily care or need to know. A React Context provider or global app state helps solve this problem. – Drew Reese Jan 16 '23 at 18:44
  • Thanks you guys! I solved my problems just by fixing my login call from: .then((response) => { if (response.data.accessToken) to: .then((response) => { if (response.data) – Bigbool98 Jan 16 '23 at 18:51

0 Answers0