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

133
Views
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 answers
Answer question

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 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!