• Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Precios
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

89
Vistas
React Router (Version 6.0.2) makes page unresponsive ReactJS

When I use the new navigate function in ReactJS React Router DOM it makes the page unresponsive. I think there is an error in my code because when I add the navigate react-router-dom function to a button like () => navigate('home') it works. But, when I add it in useEffect it doesn't work, the page becomes unresponsive.

Please check my code if there are any errors because I do not know a lot about this.

import React, { useEffect, useState } from 'react';

import './App.css';

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link,
  Navigate,
  useNavigate
} from "react-router-dom";
import Home from './Pages/Home';
import Login from './Pages/Login';

import {
  getAuth,
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  onAuthStateChanged
} from "firebase/auth";

import {auth} from './Config';


function App() {

  const [authenticated, setAuthenticated] = useState(false);

  const navigate = useNavigate();

  useEffect(() => {
    onAuthStateChanged(auth, (user) => {
      if (user) {
        setAuthenticated(true);
        navigate('home') // doesn't work
      } else {
        setAuthenticated(false);
      }
    })
  })

  const signup = (email, pass) => {
    createUserWithEmailAndPassword(auth, email, pass)
      .then((userCredential) => {
        const user = userCredential.user;
        console.log(user)
        navigate('home')
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.log(errorMessage)
      });
  }

  const login = (email, pass) => {
    signInWithEmailAndPassword(auth, email, pass)
      .then((credentials) => {
        console.log(credentials.user);
      })
      .catch((error) => {
        console.log(error.message);
      })
  }

  return (
    <Routes>
      <Route path='/' element={<button className="primary-button" onClick={() => navigate('home')}>Home</button>} /> // this works
      <Route path="/home" element={<Home authenticated={authenticated} />}></Route>
      <Route path="/auth" element={<Login signup={signup} login={login} />}></Route>
    </Routes>
  );
}

function AppWrapper() {
  return (
    <Router>
      <App />
    </Router>
  )
}

export default AppWrapper;
9 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

My guess would be from the code that you are render looping since the useEffect hook is missing a dependency array. Each time App renders it looks like it recreates the auth listener and likely triggers a rerender.

Add the dependency array to the useEffect so it's only called once on component mount and return the unsubscribe function in the effect cleanup function.

useEffect(() => {
  const unsubscribe = onAuthStateChanged(auth, (user) => {
    if (user) {
      setAuthenticated(true);
      navigate('home');
    } else {
      setAuthenticated(false);
    }
  });

  return unsubscribe;
}, []); // <-- empty dependency == call once on mounting
9 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.