Reputation:
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:
What is the most efficient way to redirect to other pages in Next.js after a function and/or requests?
Upvotes: 4
Views: 12979
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
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