I am new to react, I am trying to create a form with some fields. but I don’t know how to clear my input field after inserting data and I would also like my select option to go back to the default “Select option”.
const AddBook = () => {
const [authors, setAuthors] = useState([]);
const [book, setBook] = useState([]);
const { loading, data } = useQuery(getAuthorsQuery)
const [addBook] = useMutation(addBookMutation)
const handleSubmit = (e) => {
e.preventDefault();
addBook({
variables: {
name: book.name,
genre: book.genre,
authorId: book.authorId
},
refetchQueries:[{query:getBooksQuery}]
})
}
const handleChange = (e) => {
setBook({...book,[e.target.name]: e.target.value})
}
useEffect(() => {
if (!loading) {
setAuthors(data.authors)
}
}, [data, loading]);
return (
<form id="add-book" onSubmit={handleSubmit}>
<div className='field'>
<label>Book name</label>
<input type="text" name="name" onChange={handleChange}/>
</div>
<div className='field'>
<label>Genre</label>
<input type="text" name="genre" onChange={handleChange}/>
</div>
<div className='field'>
<label>Author</label>
<select name="authorId" onChange={handleChange}>
<option>Select Option</option>
{authors.map(author => <option name="authorId" key={author.id} value={author.id}>{author.name}</option>)}
</select>
</div>
<button>Add Book</button>
</form>
)
};
export default AddBook