How do I revalidate and redirect?
Unanswered
Sloth bear posted this in #help-forum
Sloth bearOP
If I create a product in /add-product and want to revalidate the home page and get redirect there.
I'm doing it this way but it doesn't feel right. Any idea?
'use server'
import prisma from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
export const createProduct = async (formData: FormData) => {
const name = formData.get('name')?.toString()
const description = formData.get('description')?.toString()
const price = parseFloat(formData.get('price') as string)
const amount = parseInt(formData.get('amount') as string, 10)
if (!name !description !price || !amount) {
return
}
const existingProduct = await prisma.product.findFirst({
where: { name },
})
if (existingProduct) {
return false
}
await prisma.product.create({
data: {
name,
description,
price,
amount,
},
})
revalidatePath('/')
redirect('/')
}
I'm doing it this way but it doesn't feel right. Any idea?
'use server'
import prisma from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
export const createProduct = async (formData: FormData) => {
const name = formData.get('name')?.toString()
const description = formData.get('description')?.toString()
const price = parseFloat(formData.get('price') as string)
const amount = parseInt(formData.get('amount') as string, 10)
if (!name !description !price || !amount) {
return
}
const existingProduct = await prisma.product.findFirst({
where: { name },
})
if (existingProduct) {
return false
}
await prisma.product.create({
data: {
name,
description,
price,
amount,
},
})
revalidatePath('/')
redirect('/')
}
2 Replies
Southeastern blueberry bee
this works ?
@Southeastern blueberry bee this works ?
Sloth bearOP
I mean yeah, but it feels slow. I don’t know if this is the right way