Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
Redirect using navigate() to the same URL updating the state in react

'/'URL Login handler function

const loginHandler = (e) => {
        e.preventDefault();
        Services.login(email, password)
          .then((Res) => {
            if(Res.data==="success"){
              navigate('/home')
            }
            else {
              navigate('/',{
                state: {
                  msg: Res.data,
                }})
            }
          })
          .catch((error) => {
            console.log(error);
          });
      };

On Res.data other than success I want to redirect to the same /Url by updating the state of a component so that I can display proper error message on the same page and prevent user to navigate to /home Url . How can I do that?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think you'll find it's not too useful to navigate to the same page as you intend. Seems more straightforward to keep some state on the current page and show/hide an error message based on that state

import React, { useState } from 'react';

const ThisPage = () => {
    const [failed, setFailed] = useState(false);
    
    const loginHandler = () => {
        ....when you get to your error
        }else{
            setFailed(true);
        }
    }
    //then render an error message on this page if failed
    return(
        <div>
            <SomeOtherContent />
            <div hidden={!failed}>Something went wrong!</div>
        </div>
    );
}

If you really need to navigate to the same page, you could look into using useContext() to keep a state that is outside of the page component so that it would still be there when you redirect to the same component (and rerender it). https://reactjs.org/docs/hooks-reference.html#usecontext

about 4 years 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 vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda