Next.js Discord

Discord Forum

How do I redirect to an edit page with the ID as a query parameter after form submission in Next.js?

Unanswered
Chinese Alligator posted this in #help-forum
Open in Discord
Chinese AlligatorOP
I'm building a book management application using Next.js. I have a form that collects book details and submits them using an asynchronous function (onSubmit). The form data is sent to an action.ts file where it is validated and inserted into a Supabase database. After a successful submission, I want to redirect the user to an edit page while passing the ISBN of the newly submitted book in the URL.

Full post: https://stackoverflow.com/questions/79510632/how-do-i-redirect-to-an-edit-page-with-the-id-as-a-query-parameter-after-form-su

//submitting the forms
  async function onSubmit(data: BookInferSchema) {
    try {
      const formData = new FormData();
      Object.entries(data).forEach(([key, value]) => {
        formData.append(
          key,
          value instanceof Date ? value.toISOString() : value.toString()
        );
      });

      //sending the formData to the action.ts for submitting the forms
      const response = action(formData) as {
        error?: string;
        message?: string;
      } | void;

      //Error or success messages for any submissions and any errors/success from the server
      if (response?.error) {
        toast({
          title: "Error",
          description: `An error occurred: ${response.error}`,
        });
      } else {
        //after submitting the form, reset the form
        // form.reset();
      }
    } catch {
      toast({
        title: "Error",
        description: "An unexpected error occured.",
      });
    }
  }


And here’s a snippet of my action.ts where I validate and insert the book into the database:

const supabase = createClient();
const { data, error } = await (await supabase)
  .from('books')
  .insert({
    isbn: ISBN,
    // ... other fields
  });

if (error) {
  return {
    error: true,
    message: error.message,
  };
}

return {
  error: false,
  message: 'Book updated successfully',
};

2 Replies

Spectacled bear
What is the issue here? If i understood correctly, do it inside the else block where the flow come on success case.
You can use useRouter from next/navigation to redirect.
Blood cockle
you could redirect to the relevant route using a dynamic route.
https://nextjs.org/docs/app/building-your-application/routing/redirecting

so you would need a page using a [ISBN] dynamic route like
@/app/books/[ISBN]
redirect('/books/[ISBN]')