Next.js Discord

Discord Forum

Redirect From next/navigation Not Working

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Avatar
Sloth bearOP
&765954582710583336 Hello I am facing an issue with official nextjs.org learn course 'https://nextjs.org/learn/dashboard-app/mutating-data' i have taken it and build a dashboard with it but facing issue with redirect hook from next/navigation in server component function. it's not redirecting to /dashboard/invoices page instead giving an error of NEXT_REDIRECT in docs 'https://nextjs.org/docs/app/api-reference/functions/redirect' i have discovered that Invoking the redirect() function throws a NEXT_REDIRECT error and terminates rendering of the route segment in which it was thrown. instead i used the useRouter from next/navigation. so what is the purpose of redirect from next/navigation when it doesn't work. here is my code from action.ts
'use server';

import { z } from 'zod';
import { sql } from '@vercel/postgres';
import { revalidatePath } from 'next/cache';
import { useRouter } from 'next/navigation';
import { redirect } from 'next/navigation';


export async function createInvoice(formData: FormData) {

const { customerId, amount, status } = CreateInvoice.parse({
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status')
})

const date = new Date().toISOString().split('T')[0]
const amountInCents = amount * 100

try {
await sql
INSERT INTO invoices (customer_id, amount, status, date)
VALUES (${customerId}, ${amountInCents}, ${status}, ${date})

} catch (error) {
return {
message: 'Database Error: Failed to Create Invoice.'
};
}
}

revalidatePath('/dashboard/invoices')
redirect('/dashboard/invoices')

0 Replies