0

I am trying to fetching an api and wanted to render it on the DOM using react using useState hook but hook works perfectly in second time but returns undefined first time as state was not updated and it says Cannot read properties of undefined (reading 'cards') as state was not updated and remains an empty object someone please help

    import { useParams } from "react-router-dom";

    import { useEffect, useState } from "react";
    import { IMAGE_CDN_URL } from "../config";
    
    const ResturentMenu = () => {
      // how to raed Dynamic url
      // const{id}=useParams() direct destructuring
      const params = useParams();
      const { resId } = params;
      const [restaurant, setRestaurent] = useState({});
      useEffect(() => {
        getResturentInfo();
      }, []);
      
      async function getResturentInfo() {
      
          const data = await fetch(
            "https://www.swiggy.com/dapi/menu/pl?page-type=REGULAR_MENU&complete-menu=true&lat=26.7999454&lng=75.8138096&restaurantId=72060&catalog_qa=undefined&submitAction=ENTER"
          );
          
          setRestaurent(await data.json());
          
          console.log(restaurant);
          
           console.log(restaurant.data.cards[0].card.card.info.id)
      
      }
      console.log(restaurant.data.cards[0].card.card.info.name);
     
 
    
      console.log(resId);
      
      return (
        <>
        <div>
          <h1>Resturent id:{resId}</h1>
          {/* <h2>{restaurant.data}</h2>  */}
          <h2>{restaurant.data.cards[0].card.card.info.name}</h2> 
          <img src={IMAGE_CDN_URL+restaurant.data.cards[0].card.card.info}></img> 
        </div>
        </>
      )
      
      
    };
    export default ResturentMenu; 

 

I tried setting setresturent(await...) but it not working

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • I just woke up, basically you should render cards only if it exists, so add the condition before displaying it. – Eugene Jul 21 '23 at 08:43

0 Answers0