I am trying to iterate over the response I get from an API using the map()
method but I keep getting the error ‘drinks.map is not a function’. Below is my code
Drinks
import DrinksList from "@/components/DrinksList";
const url = "https://www.thecocktaildb.com/api/json/v1/1/search.php?f=a";
const fetchDrinks = async () => {
await new Promise((resolve) => setTimeout(resolve, 1000));
const response = await fetch(url);
// throw error
if (!response.ok) {
throw new Error("Failed to fetch");
}
const data = await response.json();
return data;
};
const Drinks = async () => {
const data = await fetchDrinks();
return (
<div>
<DrinksList drinks={data} />
</div>
);
};
export default Drinks;
I have tried checking if I had any typos.
2
Answers
The basic issue is that the fetched data is an object with a
drinks
property that is the array you would like to render.The code is passing this object as the
drinks
prop and trying to call amap
method that is undefined, e.g. the error message that "map is not a function".Additionally, React components are synchronous. They cannot be declared
async
since this implicitly returns a Promise object and this is not valid JSX to be rendered to the DOM.Wrap asynchronous logic in a
useEffect
hook. If you are fetching data then you’ll want some state to hold the data you want to render, e.g. map to valid JSX.It’s a good idea to also provide a default value for the
drinks
prop in case you render aDrinksList
component and pass an undefineddrinks
prop.I think you need to iterate
drinks
like this. Sincedrinks
is an Array whose first element is an object calleddrinks
which again is an Array of Objects.So I guess you can use
map()
function like this ondrinks
.