Daniel Santos
Daniel Santos

Reputation: 113

Using the Next.Js App Router, how can I submit a form on one page and pass the form results as arguments in a function on another page?

Context I am working on a Next.JS project (App router). It is vaguely similar to a travel booking website, such as Skyscanner. On my home page (home.js), I have a form. Submitting the form will automatically redirect to a results page (results.js). My results page features a function which makes a call to my python backend - the output of this function enables the page content to be shown. However, it requires arguments (which are in the jsonified-output of the form). Note, both pages are server page (although the form is a client-side component), and I would like to avoid changing either page to "use client".

Question I would like to be able to access the form values on results.js as soon as it starts building. How best can I achieve this?

What I've Tried I have tried passing the arguments through to the URL (e.g. using useRouter), but would like to avoid this since one of my arguments is the users' current location, which I would rather keep private. I also considered using React Context API - but Next.JS documentation says this is no longer supported in server components.

Thanks in advance!

Upvotes: 0

Views: 895

Answers (1)

Daniel Santos
Daniel Santos

Reputation: 113

I managed to figure out a solution for this question. It involves using "server actions" (currently still an experimental feature in Next.js).

I created a file marked "use server", which exported a server function. That function took an argument, created cookies from it, then redirected to my results page.

I then called this server function as a result of my form submission on my client "home" page, with my jsonified form data as the argument. I could then access the relevant cookie on my "results" page.

Hope this helps someone :)

Upvotes: 1

Related Questions