user15067897
user15067897

Reputation:

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?

Upvotes: 4

Views: 12979

Answers (2)

IonicMan
IonicMan

Reputation: 902

I also had my initialization of useRouter in my function. I fixed the same bug by placing that line into my function component instead of my function and calling router.push(...) in the function itself.

Upvotes: 0

W1ndstorm
W1ndstorm

Reputation: 156

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.

Upvotes: 8

Related Questions