简体   繁体   中英

map function not working for API data in useEffect - React Hooks

The code below is not populating the UL with any items. The only item populated is the "Default LI" that I manually put in there. The console output shows data in response.data. All of the console.log calls show output, so everything appears to be firing. Probably something really simple. Any help appreciated. Thanks!

import React, { useEffect, useState } from "react";
import axios from "axios";

export default function AssetTypes() {
  const [data, setData] = useState({ items: [] });

  useEffect(() => {
    console.log("inside useEffect");
    let url = `https://localhost:5001/api/AssetTypes?organizationId=999`;
    console.log(url);

    console.log("useEffect 1");
    const fetchData = async () => {
      console.log("fetchData 1");
      const response = await axios.get(url);
      console.log("fetchData 2");
      console.log(JSON.stringify(response.data));
      console.log("fetchData 3");
      setData(response.data);
      console.log("fetchData 4");
    };
    console.log("useEffect 2");
    fetchData();
    console.log("useEffect 3");
  }, []);

  return (
    <>
      <h1>Asset Types</h1>
      <ul>
        <li>Default LI</li>
        {data &&
          data.items &&
          data.items.map((item) => (
            <li key={item.assetTypeId}>
              <span>
                {item.assetTypeName} - {item.assetCategory}
              </span>
            </li>
          ))}
      </ul>
    </>
  );
}

Stringify output:

[{"assetTypeId":2,"organizationId":0,"assetTypeName":"Book","assetCategory":"Book"},{"assetTypeId":4,"organizationId":0,"assetTypeName":"eBook","assetCategory":"Digital"},{"assetTypeId":6,"organizationId":0,"assetTypeName":"Magazine","assetCategory":"Periodical"},{"assetTypeId":8,"organizationId":0,"assetTypeName":"Newspaper","assetCategory":"Periodical"},{"assetTypeId":9,"organizationId":0,"assetTypeName":"Encyclopedia","assetCategory":"Book"}]

Thanks to Chris Farmer. Here are the changes I made. It was something stupid, just as expected!

const [data, setData] = useState([]);

...    

{data &&
          data.map((item) => (
            <li key={item.assetTypeId}>
              <span>
                {item.assetTypeName} - {item.assetCategory}
              </span>
            </li>
          ))}

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