Home > Mobile >  not able to display fetched data on page ReactJS
not able to display fetched data on page ReactJS

Time:04-21

in the code below i am fetching data from an API and want to display it on a page.

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 did almost every method which i found on stackoverflow but still can't resolve the error. In frontend i have used ReactJS and in Backend i am using NodeJS

here is the screenshot of the error i am getting

CodePudding user response:

Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator (||):

let foo;

//  foo is never assigned any value so it is still undefined
let someDummyText = foo || 'Hello!';

However, due to || being a boolean logical operator, the left hand-side operand was coerced to a boolean for the evaluation and any falsy value (0, '', NaN, null, undefined) was not returned. This behavior may cause unexpected consequences if you consider 0, '', or NaN as valid values.

I recommend change your || operator to ?? like:

(products ?? [])

because this '??' operator will conditions if you receive nullish value.

if you want to know more check it out here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

CodePudding user response:

I think the challenge you are having is from your display function. You should return a Jsx element before mapping the products and enclose the mapping function in the curly ({}) bracket so React knows you are now writing javascript.

const display = () => {

  return (<React.Fragment>
{(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>}))
</React.Fragment>
    );
  
 }

Also I think you should use <td>{product.name}</td>... to return table data and not <th>{product.name}</th>

  • Related