Server actions with prefilled values?
Answered
West African Crocodile posted this in #help-forum
West African CrocodileOP
What is the flow here?
Let's say I have a form with inputs that should be prefilled from the server, but editable by the user?
You need to opt in for useState in this case with the onChange handler? Or is there a new way to do it with formData and server actions?
Let's say I have a form with inputs that should be prefilled from the server, but editable by the user?
You need to opt in for useState in this case with the onChange handler? Or is there a new way to do it with formData and server actions?
Answered by Turkish Van
Since You are on the Server Component, You can fetch the data and set it as the
Let's say You had a function which retrieves some data:
Your Server Component might look like this:
defaultValue of the appropriate input element:Let's say You had a function which retrieves some data:
const getData = async () => {
await new Promise((resolve) => setTimeout(resolve, 500));
return { username: "johndoe" };
};Your Server Component might look like this:
const Page = async () => {
const data = await getData();
const signIn = async (formData: FormData) => {
"use server";
console.log(formData);
// Do something with form data
};
return (
<form action={signIn}>
<input type='text' name='username' defaultValue={data.username} />
<button type='submit'>Login</button>
</form>
);
};
export default Page;4 Replies
@West African Crocodile What is the flow here?
Let's say I have a form with inputs that should be prefilled from the server, but editable by the user?
You need to opt in for useState in this case with the onChange handler? Or is there a new way to do it with formData and server actions?
Turkish Van
If I understood it properly, You want to pre-fill some of the form inputs with the data that is fetched from somewhere. After that user should be able to modify these inputs. Right?
West African CrocodileOP
Exactly 👍
@West African Crocodile Exactly 👍
Turkish Van
Since You are on the Server Component, You can fetch the data and set it as the
Let's say You had a function which retrieves some data:
Your Server Component might look like this:
defaultValue of the appropriate input element:Let's say You had a function which retrieves some data:
const getData = async () => {
await new Promise((resolve) => setTimeout(resolve, 500));
return { username: "johndoe" };
};Your Server Component might look like this:
const Page = async () => {
const data = await getData();
const signIn = async (formData: FormData) => {
"use server";
console.log(formData);
// Do something with form data
};
return (
<form action={signIn}>
<input type='text' name='username' defaultValue={data.username} />
<button type='submit'>Login</button>
</form>
);
};
export default Page;Answer
West African CrocodileOP
Thank you it was the defaultValue prop I needed 👌