简体   繁体   中英

I am not able to retrive my data from api showing error " Cannot read properties of undefined " ,sometime i recieve data and most of the time i don't

useFetch.js

 useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const res = await axios.get(url);
        setData(res.data);
      } catch (err) {
        setError(err);
      }
      setLoading(false);
    };
    fetchData();
  }, [url]);

PropertyList.jsx

import React from "react";
import useFetch from "../../hooks/useFetch";
import "./propertyList.css";

function PropertyList() {
  const { data, loading, error } = useFetch(
    "http://localhost:3000/api/hotels/countByType"
  );

  console.log(data);

  const images = [
    "https://media-cdn.tripadvisor.com/media/photo-s/1c/d3/b2/4f/exterior-view.jpg",
    "https://www.phillyaptrentals.com/wp-content/uploads/2020/12/apartment-building-what-makes-good-apartment-building-scaled.jpg",
    "https://dynamic-media-cdn.tripadvisor.com/media/photo-o/1a/01/04/c9/manduna-resort.jpg?w=900&h=-1&s=1",
    "https://images.squarespace-cdn.com/content/v1/585562bcbe659442d503893f/c3b765c0-45e3-46b3-9ff9-b4101fb30674/01.+Exotik+Villas+Bali+-+Aloui.jpg",
    "https://vancouverisland.travel/app/uploads/2021/04/wood-cabin-on-vancouver-island_BenGiesbrecht.jpg",
  ];

  return (
    <div className="pList">
      {loading ? (
        "Loading.."
      ) : (
        <>
          {data &&
            images.map((img, i) => (
              <div className="pListItem" key={i}>
                <img src={img} alt="" className="pListImg" />
                <div className="pListTitles">
                  <h1>{data[i].type}</h1>
                  <h2>
                    {data[i].count} {data[i].type}
                  </h2>
                </div>
              </div>
            ))}
        </>
      )}
    </div>
  );
}

export default PropertyList;

I think this may be because of fetching API into the res variable after PropertyList.jsx page calls the data state into the map function

**output of API : ** [ { "type": "hotel", "count": 6 }, { "type": "apartments", "count": 0 }, { "type": "resort", "count": 0 }, { "type": "villas", "count": 0 }, { "type": "cabins", "count": 0 } ]

Do you know what's the reason behind this error?

res.data, data key is missing in API response, so in this case you need to add conditions

The conditions is -

const res = await axios.get(url); setData(res.data);

S/B

const res = await axios.get(url);

const data = (res.data !== undefined) ? res.data : [];

setData(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM