soccerway
soccerway

Reputation: 12009

React hooks form doesn't reset the text fields even after submitting the data

React hooks form doesn't reset the text fields even after submitting the data to server. I have called setRegister({...initialState}); but it doesn't care and not resetting the fields, can someone please advise what could be the reason ?

const [formRegister, setRegister] = useState({ _id: "", nomineename: "", email: "", description: "", nominatedby: ""});

const onChange = (e) => {
    e.persist();
    setRegister({ ...formRegister, [e.target.name]: e.target.value });
}
const initialState = {
    _id:"",
    nomineename: "",
    email: "",
    description: "",
    nominatedby: ""
};
const onSubmit = () => {
        const fetchData = async () => {
            try {
                const res = await Axios.post('http://localhost:8000/service/nominateperson', formRegister);
                if (res.data) {
                    console.log("Link token created:" + res.data);
                    const successMessage = res.data.message;
                    setHelperText(successMessage);
                    setRegister({...initialState});
                }
            } catch (e) {
                console.log(e);
                history.push('/errorPage');
            }
        }
        fetchData();
    }

return (
        <div className="App">
            <h1>Nominate Person</h1>
            <form onSubmit={handleSubmit(onSubmit)}  className="linkForm inputForm" >
                <div className="inputField" >
                    <input name="nomineename" 
                    placeholder="nominate a person" 
                    type="text" 
                    {...register('nomineename',{
                        required: "Nominate a person is required !",
                        pattern: {
                          value: /^[a-zA-Z\s]/,
                          message: "Invalid name !"
                        }
                      })
                    }
                      onChange={onChange}
                    /> 
                </div>
                <span className="nominateError"><pre>{errors.nomineename && errors.nomineename.message}</pre></span>
                <div className="inputField" >
                    <input name="email" 
                    placeholder="nominee email" 
                    type="text" 
                    {...register('email',{
                        required: "Nominee email is required !",
                        pattern: {
                            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                           message: "Invalid email address !"
                        }
                      })}
                      onChange={onChange}
                    />
                </div>
                <span className="nominateError"><pre>{errors.email && errors.email.message}</pre></span>
                <div className="inputField" >
                    <textarea name="description" 
                    placeholder="reason for nomination"
                    {...register('description',{
                        required: "Description is required !",
                        pattern: {
                            value: /^[a-zA-Z,.!""\s]{10,1000}$/,
                            message: "Min of 10 or not more than 1000 characters !"
                        }
                      })}
                      onChange={onChange}
                    />
                </div>
                <span className="nominateError"><pre>{errors.description && errors.description.message }</pre></span>
                <div className="inputField nominatedby" >
                    <input name="nominatedby" 
                    placeholder="nominated by" 
                    type="text" 
                    {...register('nominatedby',{
                        required: "Nominated by is required !",
                        pattern: {
                          value: /^[a-zA-Z\s]{2,30}$/,
                          message: "Invalid name !"
                        }
                      })}
                      onChange={onChange}
                    /> 
                </div>
                <span className="nominateError"><pre>{errors.nominatedby && errors.nominatedby.message}</pre></span>
                <span className="getlinkbutton">
                    <input type="submit"/>
                </span><br></br><br></br>
                <label>
                    <span className="loginValidationText">{helperText}</span>
                </label>
            </form>
        </div>
    )

https://codesandbox.io/s/xenodochial-tereshkova-51t97?file=/src/App.js

Upvotes: 0

Views: 1408

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53994

The form state is controlled by useForm and not by your formRegister state.

Therefore, to reset form fields/state, you need to use its reset API.

const { reset } = useForm();

const onSubmit = () => {
  reset(initialState);
  const fetchData = async () => {
    try {
      ...
      if (res.data) {
        ...
        reset(initialState);
        setRegister({ ...initialState });
      }
    } catch (e) {
      ...
    }
  };
  fetchData();
};

Upvotes: 1

Related Questions