skip to Main Content

I am trying to redirect the user from the error page in the app folder back to the main page.
I am building a weather , so in case the user inputs a wrong city he should be able to go back to the Home Screen. I tried using router but it didn’t work.here is the error page

"use client";
import Nav from "@/components/Nav";
import Wrapper from "@/components/Wrapper";
import { useRouter } from "next/navigation";
const Error = ({ error, reset }) => {
  const router = useRouter();
  const handleGoBack = (e) => {
    e.preventDefault();
    console.log("go back");
    router.push(`/?city=london`);
  };
  return (
    <div>
      <form onSubmit={handleGoBack}>
        <button>go back</button>
      </form>
    </div>
  );
};

export default Error;


I also tried using next() but it just retry the fetch the wrong city.

2

Answers


  1. Next 13 has a few helpers that they export from next/navigation, including redirect. If you want to redirect on the server, then:

    import { redirect } from 'next/navigation'
    

    Then:

    redirect('/?city=london')

    however you need it in your page/action.

    Login or Signup to reply.
  2. import Link from "next/link";
    
    // you dont need form, Link is enough
    <Link 
         href={{
                pathname: "/",
                query: {
                   city:"London"
                },
           }}
      >       
        Back to home
      </Link>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search