I’m trying to rendering Google Books API, just the user have to write in a input field to find a book and the title appers. But when the user delete all the field, the apps colapse and send me this error message
Cannot read property ‘length’ of undefined. And i been trying using conditional like " if length === 0 " but i recive same error.
CodeSandBox: https://codesandbox.io/s/busy-banzai-jcc69?file=/src/components/Add.js
Error message:
Code:
import React, { useState } from "react";
export const Add = () => {
// Hooks~
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
// Functions =>
const handleChange = (e) => {
e.preventDefault();
setQuery(e.target.value);
fetch(
`https://www.googleapis.com/books/v1/volumes?q=${e.target.value}&key=AIzaSyDmmCThZovxSFYPvCUaUB6h4c5gYCJeUnw`
)
.then((res) => res.json())
.then((data) => {
!data.errors ? setResults(data.items) : setResults([]);
});
};
return (
<div>
<div>
<div>
{/* Searchbar */}
<div>
<input
type="text"
placeholder="Search for a book"
value={query}
onChange={handleChange}
/>
</div>
{/* Rendering Fetch Data */}
{results.length > 0 && (
<ul>
{results.map((book) => (
<li key={book.id}>
<h3>{book.volumeInfo.title}</h3>
</li>
))}
</ul>
)}
</div>
</div>
</div>
);
};