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
Solution
import { useMutation, useQuery } from '@apollo/client'
import React, { useEffect, useRef, useState } from 'react'
import { addBookMutation, getAuthorsQuery, getBooksQuery } from '../queries/queries';
const AddBook = () => {
const initalState = {
name: "",
genre:""
}
const [authors, setAuthors] = useState([]);
const [book, setBook] = useState(initalState);
const { loading, data } = useQuery(getAuthorsQuery)
const [addBook] = useMutation(addBookMutation)
**const selectElement = useRef(null)**
const handleSubmit = (e) => {
e.preventDefault();
addBook({
variables: {
name: book.name,
genre: book.genre,
authorId: book.authorId
},
refetchQueries:[{query:getBooksQuery}]
})
**setBook(initalState)
selectElement.current.value = ""**
}
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" value={book.name} onChange={handleChange}/>
</div>
<div className='field'>
<label>Genre</label>
<input type="text" name="genre" value={book.genre} onChange={handleChange}/>
</div>
<div className='field'>
<label>Author</label>
**<select ref={selectElement} name="authorId" onChange={handleChange}>
<option value="">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