import { getAllProducts } from "../API";
const Products = () => {
const [items, setItems] = useState([]);
useEffect(() => {
getAllProducts()
.then((res) => {
setItems(res.data);
})
.catch(err => {
console.log(err)
})
}, []);
return (
<List
grid={{
gutter: 16,
xs: 1,
sm: 2,
md: 4,
lg: 4,
xl: 6,
xxl: 3,
}}
dataSource={items}
renderItem={(item) => (
<List.Item>
<Card
key={item.id}
title={item.title}
cover={<Image src={item.thumbnail} />}
>
</Card>
</List.Item>
)}
/>
);
}
export default Products;
export const getAllProducts = () => {
return (
fetch('https://dummyjson.com/products')
.then(res => res.json())
.then(console.log)
)
}
The issue is that your last .then
callback in getAllProducts
calls console.log
with the data and then returns the return value of console.log
, which is undefined
. This becomes the first argument of the .then
callback in your useEffect
. If you want to add logging, you still have to return the data so it can be accessed in the next .then
handler in the chain.
return fetch('https://dummyjson.com/products')
.then(res => res.json())
.then(res => {
console.log(res);
return res;
});
In addition, the sample JSON returned has no data
property. Its products
property is an array though.
setItems(res.products);