mateoc15
mateoc15

Reputation: 654

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"}]

Upvotes: 1

Views: 846

Answers (1)

mateoc15
mateoc15

Reputation: 654

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>
          ))}

Upvotes: 2

Related Questions