React useState hook is not updated

  Kiến thức lập trình

When I run my frontend and backend, Axios makes a request to the specified route and logs the status of the response to the console. However, even after successful login, the ‘auth’ state does not update. How can I fix this issue?

//PrivateRoute.js
import React, { useState, useEffect } from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import axios from 'axios';

const PrivateRoute = () => {
  const [auth, setAuth] = useState(false);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const response = await axios.get('/api/users/protected', {withCredentials: true});
        console.log('Status: ', response.status)
        if (response.status === 200) {
            setAuth(true);
        }
      } catch (error) {
            setAuth(false);
      }
    };
    checkAuth();
  }, []);

  console.log('Auth: ', auth);
  return auth ? <Outlet /> : <Navigate to="/" />;
};

export default PrivateRoute;

Status: 200
Auth: false

//Expecting on successfull
Auth: true

//Result
Auth: false

New contributor

Pratham Porwal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT