skip to Main Content

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
enter image description here

Can anyone point out what am i doing wrong

2

Answers


  1. The problem is that:

    1. resp.data.drinks is not an array.
    2. Or in CocktailCard function you try invoke .map() on object. Try to change it from data.map() to data.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.

    Login or Signup to reply.
  2. try debugger in your code line in both files) you will clearly see what is what there

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search