I'm working with GoogleBooks API and I can get from the API the object that I need, and from there all the values I want. e.g.
console.log("item", item); // full object
console.log("title", item.volumeInfo.title); // title
but when I want to get nested objects I get an error:
console.log(item.volumeInfo.imageLinks.smallThumbnail);
TypeError: Cannot read property 'smallThumbnail' of undefined
So I created a this:
const BookItem = ({ item }) => {
const dispatch = useDispatch();
...
useEffect(() => {
const objSource = item.volumeInfo.imageLinks;
const getImages = Object.values(objSource);
console.log(getImages);
//eslint-disable-next-line
}, []);
const clickAddToStore = () => {
setAddToStore(true);
};
const clickRemoveFromStore = () => {
setAddToStore(false);
};
const addToDb = () => {
dispatch(
addToWooDb(
item.volumeInfo,
item.searchInfo,
stockQuantity,
bookStatus,
price
)
);
};
return (
<div
className="item3"
onClick={!addToStore ? clickAddToStore : clickRemoveFromStore}
>
{item.volumeInfo.title}
</div>
...
const mapStateToProps = (state) => ({
data: state.items,
loading: state.items.loading,
});
export default connect(mapStateToProps, { addToWooDb })(BookItem);
and works perfectly, hence I can see in the console:
["http://books.google.com/books/content?id=3nMEPQAAC…J&printsec=frontcover&img=1&zoom=5&source=gbs_api", "http://books.google.com/books/content?id=3nMEPQAAC…J&printsec=frontcover&img=1&zoom=1&source=gbs_api"]
0: "http://books.google.com/books/content?id=3nMEPQAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api"
1: "http://books.google.com/books/content?id=3nMEPQAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
But strangely I still get an error:
TypeError: Cannot convert undefined or null to object
I think that I can solve it with a promise, but I never understood how they work.
Any idea?
Thanks!