Reputation: 1343
My Google Books clone application has a user submit their inputted query, then the response data is displayed.
Following the schema validation example provided by React Hook Form docs, I receive Error: Request failed with status code 400
. What am I doing wrong?
const [query, setQuery] = useState("");
const [books, setBooks] = useState({ items: [] });
const {
register,
handleSubmit,
formState: { errors }
} = useForm({
resolver: yupResolver(schema)
});
const handleBookFetch = async () => {
try {
const result = await axios.get(`${API_BASE_URL}?q=${query}`);
setBooks(result.data);
} catch (error) {
console.log(error);
}
};
<form onSubmit={handleSubmit(handleBookFetch)}>
<label name="book">
Search the world's most comprehensive index of full-text books.
</label>
<div>
<input type="text" name="book" {...register("book")} onChange={(event) => setQuery(event.target.value)} />
<p>{errors.book?.message}</p>
<button type="submit">Search</button>
</div>
</form>
Upvotes: 0
Views: 435
Reputation: 13234
Your query
state is never updated, you're not even assigning a name to the setQuery
function that useState returns. So, query
will always have its default value of "". Your server is likely returning 400 Bad Request because you're sending it an empty query string.
I think React Hook Form passes your data as an object to your handleSubmit function, so you can get the query's current value from that:
const handleBookFetch = async (data) => {
// ...
// "book" is the name of the input element
const result = await axios.get(`${API_BASE_URL}?q=${data.book}`);
// ...
};
Upvotes: 1