Home > Back-end >  Keep getting an error: listDevices.map is not a function
Keep getting an error: listDevices.map is not a function

Time:12-29

I have a Json file with information about various devices:

    {
  "devices": {
    "deviceList": [
      {
        "name": "iPhone X",
        "id": "193ywpe740",
        "deviceType": "Mobile",
        "os": "iOS",
        "brand": "Apple",
        "quantity": 3,
      },
      {
        "deviceType": "Tablet",
        "name": "Apple iPad (Wi-Fi, 32GB) - Gold",
        "brand": "Apple",
        "os": "MacOS",
        "id": "1563175150",
        "quantity": 5
      },
      {...}

My cardList js file:

import ReservationsListCard from "components/reservationsListCard";

const CardListSection = () => {
  const devices_url =
    "devices.json";

  const [listDevices, setListDevices] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const devicesResponse = await fetch(devices_url);
        const devicesJson = await devicesResponse.json();
        const [listDevices] = devicesJson.devices.deviceList;


        setListDevices(listDevices);
      } catch (error) {
        //console.log("error", error);
      }
    };

    fetchData();
  }, []);

  return (
    <div className="device-list-section">
      {listDevices.map((device) => (
        <ReservationsListCard key={device.id} />
      ))}

      {console.log(listDevices)}
    </div>
  );
};

export default CardListSection;

What I am trying to achieve is to get the "id" of every device and pass it to my ReservationsListCard component which then takes that id and displays devices name, brand, image, etc. but I keep running in to the error in the title. What could I be doing wrong ? My theory is that I am not selecting the id's of the devices. Or maybe it's a problem with the component ReservationsListCard ?

CodePudding user response:

The error is in the line

const [listDevices] = devicesJson.devices.deviceList;

You're trying to destructure (pull out the) first element of device list and assign it to list devices but you really just want to set listDevices to the device list. Try

const listDevices = devicesJson.devices.deviceList;

The error occurs because listDevices gets assigned to the first device in the list which is an object and has no map function

  • Related