Open2
ServerActions 使いながら詰まったところ
❌ formData
をそのまま渡さない
export const createTaskAction = async (formData: FormData) => {
const validatedData = createTaskSchema.safeParse(formData);
🟢 Object.fromEntries
やformData.get('inputName')
でデータを取得する
export const createTaskAction = async (formData: FormData) => {
const entries = Object.fromEntries(formData);
const validatedData = createTaskSchema.safeParse(entries);
❌ revalidatePath
やredirect
をtryブロックの中で呼ばない
try {
await db.task.create({
data: {
title: validatedData.data.title,
content: validatedData.data.content,
},
});
revalidatePath("/");
redirect("/");
} catch (error) {
throw new Error("Failed to create task");
}
🟢 try~finally
まで終了してから外で呼ぶ
try {
await db.task.create({
data: {
title: validatedData.data.title,
content: validatedData.data.content,
},
});
} catch (error) {
throw new Error("Failed to create task");
}
revalidatePath("/");
redirect("/");
Note how redirect is being called outside of the try/catch block. This is because redirect works by throwing an error, which would be caught by the catch block. To avoid this, you can call redirect after try/catch. redirect would only be reachable if try is successful.
redirectはエラーをthrowすることで動作するため。