Skip to content
Advertisement

Trying to fetch API via axios, but don’t know how to access

I try to fetch some data from an API. The API is formatted like this:

[
  {
    "1": {
      "appid": 1,
      "name": "bmw"
    },
    "2": {
      "appid": 2,
      "name": "mercedes"
    },
    "3": {
      "appid": 3,
      "name": "tesla"
    }
  }
]

And in react my app.js looks like this:

import React, { useState, useEffect } from "react";
import axios from "axios";
import ItemsGrid from "./components/items/ItemsGrid";

function App() {
  const [items, setItems] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchItems = async () => {
      const result = await axios({
        url: "http://localhost:3013/items",
        method: "get",
        timeout: 8000,
        headers: {
          "Content-Type": "application/json",
        },
      });

      console.log(result.data);
      setItems(result.data);
      setIsLoading(false);
    };

    fetchItems();
  }, []);

  return (
    <div className="App">
      <ItemsGrid isLoading={isLoading} items={items} />
      <h1>Hello</h1>
    </div>
  );
}

export default App;

And the ItemsGrid:

import React from "react";

const ItemsGrid = ({ items, isLoading }) => {
  return isLoading ? (
    <h1>Loading...</h1>
  ) : (
    <div>
      {items.map((item) => (
        <h1 key={item.appid}>{item.name}</h1>
      ))}
    </div>
  );
};

export default ItemsGrid;

So nothing is to see beacause I don’t know how to access the array. In the console log I see there is something:

[{…}]
0: {1: {…}, 2: {…}, 3: {…}}
length: 1
__proto__: Array(0)

Anyone know how to show the names via mapping?

Advertisement

Answer

If you want to turn the array with an object into a regular array you can use Object.values on the first element of the array:

useEffect(() => {
  const fetchItems = async () => {
    const result = await axios({
      url: "http://localhost:3013/items",
      method: "get",
      timeout: 8000,
      headers: {
        "Content-Type": "application/json",
      },
    });

    setItems(Object.values(result.data[0]));
    setIsLoading(false);
  };

  fetchItems();
}, []);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement