0

here i am fetching data from API which is giving me response in "array of objects" i want to store it in the array called products and want to display it on the page. Here is my code

import React, { useState, useEffect } from "react";
import '../all.css';
import Axios from "axios";


const AllProduct = () => {

const [products, setProducts] = useState([]);


const fetchProducts = async () => {
  const { data } = await Axios.get(
     "http://localhost:8080/api/QueryAllProducts"

    );
    
  console.log(data.response);
  setProducts(data.response);
  console.log(products);
  
};

const display = () => {

  return (products ?? []).map(product => (
    <tr key={product.id}>
       <th>{product.id}</th>
       <th>{product.name}</th>
       <th>{product.area}</th>
       <th>{product.ownerName}</th>
       <th>{product.cost}</th>
     </tr>
   ) );
  
 }
useEffect(() => {
  fetchProducts();
}, []);


  return (
    
    <div>

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Area</th>
      <th>Owner Name</th>
      <th>Cost</th>

    </tr>
  </thead>
  <tbody>
  {display()}

  </tbody>
  
 
</table>
    </div>
  
  
  )
}

export default AllProduct;

I have used ReactJS for frontend and NodeJS

here is the screenshot of what i am getting on console

2
  • It could be useful to get the structure of the data you are receiving. Commented Apr 22, 2022 at 6:36
  • i have added one screenshot where you can see the data i am getting through API Commented Apr 22, 2022 at 6:49

1 Answer 1

1

Check that the type of products is array. If it is an object, an error occurs.

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

6 Comments

response i am getting from api is array of objects and i want to map in products array
check typeof data.response. I think data.response is of type string.
yeah it's a string
and type of products is an object
You have to JSON.parse the data as string once. use let parseData = JSON.parse(data.response) and setProducts(parseData).
|

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.