Estoy tratando de crear un formulario con algunos campos. pero no sé cómo borrar mi campo de entrada después de insertar datos y también me gustaría que mi opción de selección vuelva a la "Opción de selección" predeterminada.
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> )};
exportar AddBook predeterminado
Solución
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