Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically navigate to other page in Next.js?

After a post request to an external API, I would like to redirect back to the homepage. I do have some knowledge with React and this is my first time using Next.js. Here is the code:

export default function New({genres}) {
const createMovie = (values) => {
    console.log(values);
    axios.post(`${process.env.NEXT_PUBLIC_BASE_URL}/movies`, {
        title: values.title,
        description: values.description,
        genres: values.genres,
        release_date: values.release_date,
        cover_url: values.cover_url
    }).then(res => {
        const router = useRouter();
        router.push('/');
    })
}

As you can see I used router.push() but I get this error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

What is the most efficient way to redirect to other pages in Next.js after a function and/or requests?


1 Answers

You need to move where you call useRouter(). You can keep router.push() where it is.

export default function New({genres}) {
    const router = useRouter();
    const createMovie = (values) => {...}
}

If you look at the Rules of Hooks, you can only call the hook, useRouter() in this case, at the top level.

like image 181
W1ndstorm Avatar answered Sep 05 '25 06:09

W1ndstorm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!