Search code examples
reactjsapiaxiosfetching-strategy

Fetching API data, nested in two arrays and displaying it with React


I am trying to fetch data that is nested in two unnamed arrays API Endpoint.

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


const API_URL = 'https://my-json-server.typicode.com/TomSearle/cb-devtest-api/products';

const MyComponent = () => {
  const [posts, setPosts] = useState([]);

  const fetchData = async () => {
    const { data } = await axios.get(API_URL);
    setPosts(data);

    console.log(data);
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      {posts.length > 0 ? (
        <div>
          {posts.map((post) => (
            <div>
              <h2>{post.price}</h2>
              <p>{post.stock_count}</p>
            </div>
          ))}
        </div>
      ) : (
        <p className="loading">Loading... </p>
      )}
    </div>
  );
};

export default MyComponent;

console.log shows an Array with 10 Objects, how could I destructure that data to display it dynamically? Any help would be appreciated.


Solution

  • Your array is nested one more level somehow. Better to fix it in the backend or simply access the posts like below.

    {
      posts[0].map((post) => (
        <div>
          <h2>{post.price}</h2>
          <p>{post.stock_count}</p>
        </div>
      ))
    }
    

    Working Demo

    Edit cool-archimedes-l9087c