Reputation: 23
In a sample nextjs app, I have a form where I can submit usernames to the server using server actions. Along side with username, I want to be able to send the timestamp of the form submission. For this I created a controlled hidden input to save the date.
Here is what I tried:
export default function Form() {
const [date, setDate] = useState("");
const [_, action] = useFormState(addUser, {});
const handleSubmit = (e) => {
e.preventDefault();
setDate(new Date().toLocaleString());
e.currentTarget.form.requestSubmit();
}
return (
<form action={action}>
<input type="text" name="username" placeholder="username" />
<input type="hidden" name="date" value={date} />
<button onClick={handleSubmit}>Add</button>
</form>
);
}
The problem is the form will be submitted before the component gets re-rendered, so value of the date input is an empty string
Upvotes: 0
Views: 2601
Reputation: 974
See this part of Learn Next tutorial and Server Actions and Mutations
I'm not sure, if you can intercept form submission the way you do. See Programmatic form submission. And use bind instead of hidden fields.
I would also think about taking the timestamp in the action and not in the form submission itself. The action seams to be the natural place for me.
Upvotes: 0