admin管理员组

文章数量:1221288

I am working with a React form component, and I have a select field inside it. When the form is submitted, I want to preserve the selected value (the default value) in the select field. However, after the form is submitted, the default value resets to the first option, which is not what I want.

This issue seems to be happening only with the <select> field, as similar behavior works with text inputs (they retain their values correctly).

How can I prevent the select field from resetting its value after the form is submitted whilst using useActionState?

import { useActionState } from "react";

function Form() {
  const [formData, formAction, isPending] = useActionState(async (previous, current) => current, new FormData);

  // After submission does log selected value
  console.log(formData.get('example'))
  
  return (
    <form action={formAction}>
      <select name="example" defaultValue={formData.get('example')}>
        <option value='1'>1</option>
        <option value='2'>2</option>                       
      </select>
      <button type='submit'>Submit</button>
    </form>
  );
}

本文标签: