skip to Main Content

I want to redirect to "/" , I am currently at "/register" route . If the response is ok then the page should be redirected to "/" path . I am trying to create a single page application with react js .

if(response.ok){
    console.log("ok");
    return redirect("/");
}
else{
    console.log("error");
}

Not being redirected to the specified route .

2

Answers


  1. assign the new location

    if(response.ok){
        console.log("ok");
        window.location.assign("/");
        return;
    }
    else{
        console.log("error");
    }
    

    you should be using guard clauses like such, to reduce code complexity and also make code simple and easy to read, and no if, else chain:

    // Handle Error
    if(!response.ok){
        console.log("error");
        return;
    }
    // Handle Success
    console.log("ok");
    window.location.assign("/");
    
    Login or Signup to reply.
  2. Gonna have to make some assumptions about the setup, but if you’re using react-router-dom, you can use its exported useNavigate hook

    // in a component
    const navigate = useNavigate()
    
    const postSomeData = (data) => {
      fetch('.../something').then(response => {
        if (response.ok) {
          console.log('ok')
          navigate('/')
        } else {
          console.log('error')
        }
      })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search