I am creating an app in which the user can search for a book using an api call. I am getting this error whenever I search for a book. The reason is because the authors array is initially undefined. But this doesn't happen with the title or the thumbnail. Any way to fix this error?
Searchpage.js
import React, { useEffect, useState } from 'react';
import { BsArrowLeftShort } from 'react-icons/bs';
import { debounce } from 'debounce';
import SearchBar from '../components/SearchBar';
import { search } from '../api/BooksAPI';
import Book from '../components/Book';
const SearchPage = () => {
const [query, setQuery] = useState('');
const [data, setData] = useState([]);
const handleChange = (e) => {
setQuery(e.target.value);
};
useEffect(() => {
const bookSearch = debounce(() => {
if (query.length > 0) {
search(query).then((res) => {
if (res.length > 0) setData(res);
else setData([]);
});
} else {
setData([]); // make sure data is not undefined
}
}, 1000);
bookSearch();
}, [query]);
return (
<div>
<SearchBar
type="text"
searchValue={query}
placeholder="Search for a book"
icon={<BsArrowLeftShort />}
handleChange={handleChange}
/>
{console.log(data)}
{data.map((book) => {
console.log(book.authors);
return (
<Book
key={book.id}
title={book.title}
authors={book.authors}
thumbnail={book.imageLinks.thumbnail}
/>
);
})}
</div>
);
};
export default SearchPage;
Book.js
import React from 'react';
import PropTypes from 'prop-types';
const Book = ({ title, authors, thumbnail }) => (
<div>
<img src={thumbnail} alt={title} />
<div>{title}</div>
<div>{authors}</div>
</div>
);
Book.propTypes = {
thumbnail: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
authors: PropTypes.arrayOf(PropTypes.string).isRequired,
};
export default Book;
EDIT: here is a screenshot of the response from the promise. I added a console.log to the promise chain. The value of the authers array does not appear as undefined. Note this appears before the warning on the console.
Try providing to Book its required property in all the cases
authors={book.authors || []}
or put authors
as not required prop in Book
otherwise