Code is not working fetching data from Swiggy API

my code is showing Error please help!

Error: Uncaught TypeError: Cannot read properties of undefined (reading 'card')

API I am using: https://www.swiggy.com/dapi/restaurants/list/v5?lat=17.486463086305346&lng=78.3657343313098&is-seo-homepage-enabled=true&page_type=DESKTOP_WEB_LISTING

My code:

import React, { useState, useEffect } from "react";
import RestraurentCard from "../components/RestraurentCard";
import resList from "../utils/mockData";

const Body = () => {
  const [listOfRestrarent, setListOfRestraurent] = useState(resList);

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    // Log the updated state here
    console.log(listOfRestrarent);
  }, [listOfRestrarent]);

  const fetchData = async () => {
    try {
      const data = await fetch(
        "https://www.swiggy.com/dapi/restaurants/list/v5?lat=17.486463086305346&lng=78.3657343313098&is-seo-homepage-enabled=true&page_type=DESKTOP_WEB_LISTING"
      );
      const json = await data.json();
      console.log(json);
      setListOfRestraurent(
        json?.data?.cards[2]?.card?.card?.gridElements?.infoWithStyle
          ?.restaurants
      );
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <div className="body">
      <div className="filter">
        <button
          className="filter-btn"
          onClick={() => {
            let filterList = listOfRestrarent.filter(
              (res) => res.card.card.info.avgRating > 4.0
            );
            setListOfRestraurent(filterList);
          }}
        >
          Search Top rated Restaurant
        </button>
      </div>
      <div className="rest-container">
        {listOfRestrarent.map((item) => (
          <RestraurentCard key={item.card.card.info.id} resdata={item.card} />
        ))}
      </div>
    </div>
  );
};

export default Body;

Please help am stuck since yesterday

The data you’re trying to access in your React code does not match the structure of the API response. You need to adjust the fetchData function, like, you need to correctly parse and map the data to match the structure of your application. Looking from the API response, it appears that the data relevant to restaurants is deeply nested within the cards array.

Try to locate the correct path in the nested structure where the restaurant data resides. I can’t figure out just by looking.

I did some research and found this github: GitHub - Ankush11903/Foodsale: It utilizes Swiggy's live API data to fetch real-time restaurant information, and includes features such as infinite scrolling, shopping cart feature using Redux Toolkit, and UI configuration with conditional rendering and caching for better user experience. Additionally, the app implements Shimmer UI, lazy loading, and dynamic routing .

It looks like that each restaurant’s data is stored within a nested card object. Specifically, the restaurant details are located within json.data.cards.card.card.info .

I think you can update the fetchdata like this:

const fetchData = async () => {
  try {
    const response = await fetch("https://www.swiggy.com/dapi/restaurants/list/v5?lat=17.486463086305346&lng=78.3657343313098&is-seo-homepage-enabled=true&page_type=DESKTOP_WEB_LISTING");
    const json = await response.json();
    
    // Extract restaurant data from each card
    const restaurants = json.data.cards.map(card => card.card.card.info);

    // Update state with the new restaurant data
    setListOfRestraurent(restaurants);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

And don’t forget to update the rendering logic (since you’re dealing directly with the restaurant data). The mapping can be something like this, but you need to adapt to your needs:

<div className="rest-container">
  {listOfRestrarent.map((restaurant) => (
    <RestraurentCard key={restaurant.id} resdata={restaurant} />
  ))}
</div>
2 Likes

Hi…Thank you for your efforts and time you given to help me…am not able to organize the chaining of data properly and the issue is still persist.

But Thank you so much for the help!

More help would be appreciated.

Thanks in advance!

@NateDhaliwal how can I get help from more people about my code error…Please let me know.

Hi @rashmidhande1 !
Please avoid pinging people who are not in this thread.
But anyway, I am unable to help as my JavaScript isn’t proficient, let alone React.

1 Like

Hi @NateDhaliwal Oops! I thought you work for app support too…so just asked if I can get help from any other way …I am not much using this platform so dont have certain ideas on it.

Hi @rashmidhande1 !
Just a note: most of the people here are community members who help put (including me), and so is @WindLother. Staff do visit the forum regularly to monitor any bugs reported, you can notice them by the replit logo they have next to their profile picture.
I believe @WindLother can help, but may be away for now.

1 Like

Hi @NateDhaliwal,
Thank you for the information!

1 Like

I was kinda busy could not answer, can you share your repl link so I can look over your code right now?

1 Like

Hi @WindLother !
Thank you for your response… The issue has been resolved…it was just some chaining issue with the url.

Thanks Again!

hii @rashmidhande1 the same error i am getting when fetching data from your swiggy api but you can do one things that open console through chrome and reload the page. You will able to solve the problem but issue will come again once you restart react. This is temperory solution only.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.