So I’m unable to load images from https://thecatapi.com/. When I try to console log the response in fetchCatImages
, I get an array. When I console log the images in App.js
, I get a pending promise with PromiseState: “fulfilled”
and PromiseResult: Array(5)
. Can someone tell me what I’m doing wrong here?
EDITED: So I now understand async await will always return a Promise. I read through How do I return the response from an asynchronous call? but am still unsure how to get the data to display on App.js
.
import React from 'react';
import './App.css';
async function fetchCatImages() {
let images = [];
await fetch('https://api.thecatapi.com/v1/images/search?limit=5')
.then((res) => res.json())
.then((data) => (images = data))
.catch((e) => {
console.error('fetch failed!');
console.error(e);
});
console.log('file: App.js ~ line 16 ~ fetchCatImages ~ images', images);
// logs show an Array with 5 objects
return images;
}
function App() {
const images = fetchCatImages();
console.log('App.js ~ line 7 ~ App ~ images', images);
// logs shows Promise {pending}, PromiseState: “fulfilled”, PromiseResult: Array(5)
return (
<>
{!images.length ? (
<h3>There are no cats</h3>
) : (
{images.map(({ id, url }) => (
<div key={id}>
<img src={url} height={50} width={50} />
</div>
))}
)}
</>
);
}
export default App;
I also tried using try catch instead without async await and still get the same problem.
function fetchCatImages() {
let images = [];
try {
images = fetch('https://api.thecatapi.com/v1/images/search?limit=5').then((res) => res.json());
} catch (e) {
console.error('fetch failed!');
console.error(e);
}
return images;
}