Open2

ServerActions 使いながら詰まったところ

KIRAKIRA

formDataをそのまま渡さない

export const createTaskAction = async (formData: FormData) => {
const validatedData = createTaskSchema.safeParse(formData);

🟢 Object.fromEntriesformData.get('inputName')でデータを取得する

export const createTaskAction = async (formData: FormData) => {
const entries = Object.fromEntries(formData);
const validatedData = createTaskSchema.safeParse(entries);
KIRAKIRA

revalidatePathredirectを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することで動作するため。

https://arc.net/l/quote/cdqyjscd