1

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

2
  • 1
    If you're calling setData with exactly what you show here, it looks like the data is the array and there is no items property in it to iterate over. Commented Oct 7, 2020 at 20:34
  • Like I said, something simple! So I guess I'm not sure what to iterate over. The API doesn't return a "root node" like "items". So what should that look like? Is the initialization of useState done the right way for this use case? Commented Oct 7, 2020 at 20:47

1 Answer 1

2

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>
          ))}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.