DEV Community

John Bush
John Bush

Posted on

React / API returning empty array.

I have an API that's working properly in postman but not in my react app. When I call the API from react it doesn't appear to return anything. I added a console.log statement and saw that it was returning two empty arrays before returning my data four times. I can't figure out what I'm doing wrong. I've added my code below. It's one page to test a grid plugin. React is a new programming language for me.

import { RevoGrid } from "@revolist/react-datagrid";
import { useState, useEffect } from "react";
import urlApiHost from "../utils/UrlHost";

const columns = [
{
prop: "Title",
name: "Title",
size: 300,
},
{
prop: "Link",
name: "Link",
size: 500,
},
];

const selectedCat1 = "softwarestuff";
const selectedCat2 = "";

export default function LinkGrid({}) {
const [links, setLinks] = useState([]);

useEffect(() => {
const fetchLinks = async () => {
var param1 = "cat1=" + encodeURIComponent(selectedCat1);
var param2 = "cat2=" + encodeURIComponent(selectedCat2);

  var param3 = "sortDate=";

  var url = urlApiHost + "linksapi/linkslistTest/?" + param1 + "&" + param2 + "&" + param3;
  console.log("linkslist url: " + url);

  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();

    setLinks(data);
  } catch (err) {
    console.log(err);
  }
};

fetchLinks();
Enter fullscreen mode Exit fullscreen mode

}, []);

console.log(JSON.stringify(links));

const [source] = JSON.stringify(links);

return (
<>

</>
);
}

Top comments (1)

Collapse
 
john_bush_ce0b758b8a5a8c5 profile image
John Bush

Did some more testing and found the issue is not with my react API code. I added the code below and it showed the data in the unordered list as expected.

I create a dummy JSON data object inside the code and the revogrid worked when I used the static data as the source. I took that same data and put in in a JSON file, called that file using fetch and used it as the data source. The grid did not show any data or errors but the UL was populated properly. I may just move on from this plugin.

  <br></br>

  <ul>
    {links
      ? links.map((link) => (
          <li key={link.pkey}>
            {link.Title} - {link.Link}
          </li>
        ))
      : ""}
  </ul>
Enter fullscreen mode Exit fullscreen mode