Currently, I am diving into the world of Nextjs and facing a challenge in passing a variable through a form component, and then further through its server action component. (I believe this is referred to as prop drilling, and I'm exploring if there's a more elegant solution.) This variable is crucial for a database query, and I'm following a tutorial to understand it better.
As a beginner, I may make super naive mistakes, so I appreciate your understanding. My main focus right now is on accessing the value of fetchuserid for my database entry:
Here is my page.tsx where I need to pass fetchuserid through AddBalanceForm:
import { fetchUser } from "@/app/components/fetchdata";
import type { UsersDb } from "@/app/components/definitions";
import ThisUserTable from "@/app/components/thisusertable";
import AddBalanceForm from "@/app/components/addbalanceform";
export default async function Page({ params: { slug } }) {
const fetchuserid = Number(slug);
const user: UsersDb = await fetchUser(fetchuserid);
return (
<main>
<ThisUserTable user={user} />
<AddBalanceForm fetchuserid={fetchuserid}/>
</main>
);
}
In addbalanceform.tsx:
`use client';
import { useFormState } from "react-dom";
import { userAddBalance } from "./adddata";
import SubmitButton from "./submit-button";
import { EMPTY_FORM_STATE } from "./utils";
import { FieldError } from "./utils";
import { useToastMessage } from "./use-toast-message";
import { useFormReset } from "./useformreset";
export default function AddBalanceForm ({ fetchuserid }: { fetchuserid: number }) {
const [formState, action] = useFormState(
userAddBalance,
EMPTY_FORM_STATE,
);
const noScriptFallback = useToastMessage(formState);
const formRef = useFormReset(formState);
return (
<form action={action} className="flex flex-col gap-y-2" ref={formRef}>
<label htmlFor="amount">amount</label>
<textarea id="amount" name="amount" className="border-2" />
<span className="text-xs text-red-400">
<FieldError formState={formState} name="text" />
</span>
<SubmitButton label="Create" loading="Creating ..." />
<span className="font-bold">{formState.message}</span>
{noScriptFallback}
</form>
);
};
Regarding the server action:
'use server';
...
Now, I am unsure of how to pass the prop to the server action. I believe it needs to be handled in this block:
export default function AddBalanceForm ({ fetchuserid }: { fetchuserid: number }) {
const [formState, action] = useFormState(
userAddBalance,
EMPTY_FORM_STATE,
);
....
Thank you for any guidance you can provide. Much appreciated.