Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Representar un componente protegido por autenticación después de una autenticación asíncrona

Esperado: la función asíncrona verifica si el usuario está autenticado, luego devuelve verdadero, para que el componente protegido se represente, o falso, que redirige al usuario a la página de inicio de sesión.

Lo que realmente sucede: la función getAuth() devuelve "Promise", rompiendo el código.

 export default function RequireAuth({ children, redirectTo }) { const BASE_API_URL = "https://api-backend.test"; const getAuth = async () => { const isAuth = await axios .get(BASE_API_URL + "/user_auth.php", { withCredentials: true, }) .then((res) => { if (res.status === 201) { return true; } }) .catch((err) => { if (err.response.status === 401) { return false; } }); return isAuth; }; let isAuthenticated = getAuth(); return isAuthenticated ? children : <Navigate to={redirectTo} />; }

Así debería mostrarse el componente "protegido" según la documentación oficial aquí .

 <Route path="/dashboard" element={ <RequireAuth redirectTo="/login"> <Dashboard /> </RequireAuth> } />
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Tienes que hacerlo correctamente usando useEffect , prueba esto

 export default function RequireAuth({ children, redirectTo }) { const BASE_API_URL = "https://api-backend.test"; const [isAuthenticated, setAuthenticated] = useState(false); useEffect(() => { const getAuth = () => { const isAuth = axios .get(BASE_API_URL + "/user_auth.php", { withCredentials: true }) .then((res) => { if (res.status === 201) { setAuthenticated(true); } }) .catch((err) => { if (err.response.status === 401) { setAuthenticated(false); } }); }; getAuth(); }, [redirectTo]); if (isAuthenticated) { return children; } return <Navigate to={redirectTo} />; }
about 4 years ago · Juan Pablo Isaza Report

0

getAuth es una función asíncrona, por lo que devolverá una Promesa. Debe await su salida o usar .then para trabajar con la promesa resuelta.

Nota al margen, por lo general es preferible usar async/await .then o .then , pero no ambos.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!