I am working on a React project, I am trying to reset a form after clicking submit button in react but its not working. I am using useRef hook to reset a form after clicking submit button. But is not working properly. so someone please help me how to reset a form after I click submit button.
This is my code
import React, { useState, useRef } from 'react';
import './Signup.css';
import axios from 'axios';
export default function Signup() {
const [data, setData] = useState({});
const testData = async () => {
try {
const res = await axios.post('http://localhost:8000/api/user', data);
console.log(res);
} catch (error) {
console.log(error);
}
}
const handleChange = ({ target }) => {
const { name, value } = target;
const newData = Object.assign({}, data, { [name]: value });
setData(newData);
}
const handleSubmit = (e) => {
e.preventDefault();
console.log(data);
testData()
};
const myForm = useRef(null)
const resetForm = () => {
myForm.current.reset();
}
return (
<div>
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="firstname">Firstname</label>
<input type="text" className="form-control" placeholder='firstname' id="firstname" name='firstname' onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="lastname">Lastname</label>
<input type="text" className="form-control" placeholder='lastname' id="lastname" name='lastname' onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" placeholder='email' id="email" name='email' onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" placeholder='password' id="password" name='password' onChange={handleChange}></input>
</div>
<button ref={myForm} onSubmit={resetForm} type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
refis to be applied on theform