Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

Viewed 42

I am using React to build this real estate website. And it runs properly the first time but everytime i reload the site i get an error: Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

 export default function App() {
  `const [propertyData, setPropertyData] = React.useState({});`
  const [searchFilters, setSearchFilters] = React.useState(false);
  const [filterVal, setFilterVal] = React.useState({
    rentFrequency: "",
    minPrice: "",
    maxPrice: "",
    areaMax: "",
    roomsMin: "",
    bathsMin: "",
  });

  React.useEffect(() => {
    const options = {
      method: "GET",
      headers: {
        "X-RapidAPI-Key": "",
        "X-RapidAPI-Host": "bayut.p.rapidapi.com",
      },
    };

    fetch(
      `https://bayut.p.rapidapi.com/properties/list?locationExternalIDs=5002%2C6020&purpose=for-rent&hitsPerPage=9&lang=en&rentFrequency=${filterVal.rentFrequency}&priceMin=${filterVal.minPrice}&priceMax=${filterVal.maxPrice}&areaMax=${filterVal.areaMax}&roomsMin=${filterVal.roomsMin}&bathsMin=${filterVal.bathsMin}`,
      options
    )
      .then((response) => response.json())
      .then((data) => setPropertyData(data))
      .catch((err) => console.error(err));
  }, [filterVal]);


  console.log(propertyData);

  const { hits } = propertyData;

  const propertyCard = hits.map((prop) => {
    return (
      <Property
        coverPhoto={prop.coverPhoto}
        price={prop.price}
        rentFrequency={prop.rentFrequency}
        rooms={prop.rooms}
        title={prop.title}
        baths={prop.baths}
        area={prop.area}
        agency={prop.agency}
        isVerified={prop.isVerified}
        externalID={prop.externalID}
        key={prop.id}
      />
    );
  });
  
}
1 Answers

Probably propertyData is undefined before your render so it does not map. You should add control with ? so it should start like hits?.map

Related