1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you soooo much, such a simple solution and I was already trying to loop, etc. I can't change it in the backend, but this helped. Much appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.