Reset form inputs with Signal Preact

179 Views Asked by At

Is it possible to clear/reset the input fields after a form is submitted using signals? For instance, in the following simple form I have the following:

const formData = signal({ firstName: "", lastName: "" })

const Register = () => {

//function to make all keys pairs equal to an empty string
function initialState(input) {
        return Object.keys(input).forEach(i => input[i] = "");
};

function setFormData(name, value) {
        return formData.value = {...formData.value, [name]: value};
};

function handleInputChange (e) {
 const { name, value } = e.target;
 setFormData(name, value);
};
function registerUser (e){
 e.preventDefault();
 initialState(formData.value);
};

return(
  <form onSubmit={registerUser}>
   <input
    type="text"
    placeholder="First Name"
    name="firstName"
    value={formData.value.firstName}
    onChange="{handleInputChange}"
   />
   <input
    type="text"
    placeholder="Last Name"
    name="lastName"
    value={formData.value.lastName}
    onChange="{handleInputChange}"
   />
<button>Submit</button>
  </form>
)
}

From the above, what I have noticed is that the inputs get clear once I type any word in any of the input fields after I click on the submit button.

Unlike useState, everything gets clear after submitting the form, I suspect is due to the fact that it re-renders all the components, which is not the case for Signals?

Thanks in advance.

0

There are 0 best solutions below