Hi Guys the map() function seems to be not working while i am fetching an api.
Here is my Landing page
import React from 'react'
import { useLoaderData } from 'react-router-dom';
import axios from 'axios';
import CocktailCard from '../components/CocktailCard';
export const loader = async () => {
const search = 'margarita'
const url = 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s=';
const resp = await axios.get(`${url}${search}`);
return {data : resp.data.drinks};
};
function Landing() {
const dta = useLoaderData();
return (
<div><CocktailCard data = {dta}/></div>
)
}
export default Landing
I am exporting the list of cocktails from here and sending to CocktailCard page.
import React from "react";
import Wrapper from "../assets/wrappers/CocktailCard";
import CocktailList from "./CocktailList";
const CocktailCard = ({ data }) => {
const formatted = data.map((items) => {
const { strDrinkThumb, idDrink } = items;
return { id:idDrink, drinkImg: strDrinkThumb };
});
return (
<Wrapper>
{formatted.map((item) => {
return <CocktailList key={item.id} {...item}/>;
})}
</Wrapper>
);
};
export default CocktailCard;
Cocktail list is just an simple page where i intend to add functionality later
function CocktailList() {
return (
<h2>CocktailList</h2>
)
}
export default CocktailList
The error i get in the browser is this
Can anyone point out what am i doing wrong
2
Answers
The problem is that:
resp.data.drinks
is not an array..map()
on object. Try to change it fromdata.map()
todata.data.map()
.In general, you should use the console or other debugging tools to see what types and values the arguments received in functions have.
try
debugger
in your code line in both files) you will clearly see what is what there