Home > database >  How to retrieve a fetch data from a JSON?
How to retrieve a fetch data from a JSON?

Time:11-18

In a React component

import React from 'react';
export default function Customers (props) {
   const [customers, setCustomers] = React.useState([]);
   React.useEffect(() => { 
      fetch("/data.json").then(response => response.json())
      .then(data => {
         setCustomers([data])
      })
   }, []);

   return (
      <div id='Customers'>
         {customers.map(c => c.name)}
      </div>
   )

How can I display just the names of the customers from a file in the public directory called data.json ?

{
    "customers": [
        {
            "id": 542,
            "name": "E"
        },
        {
            "id": 354,
            "name": "V"
        },
        {
            "id": 54534
            "name": "A"
        }        ,
        {
            "id": 33,
            "name": "K"
        }
    ],
    "packages": [
        {
            "id": 3643453453453,
            "weight": 6343
        },
        {
            "id": 453453,
            "weight": 4534534534
        }
    ]
}

I tried using customers["customers"] or customers.customers but nothing worked...

Thanks.

CodePudding user response:

I think you should change the React.useEffect to this

React.useEffect(() => { 
  fetch("/data.json")
  .then(response => response.json())
  .then(data => {
    setCustomers(data.customers) //this is where I made the change
  });
}, []);

CodePudding user response:

import React from 'react';
export default function Customers (props) {
   const [data, setData] = React.useState({});
   React.useEffect(() => { 
      fetch("/data.json").then(response => response.json())
      .then(res => {
         setCustomers(res)
      })
   }, []);

   return (
      <div id='Customers'>
         {data && data.customers ? data.customers.map(c => c.name) : null}
      </div>
   )
  • Related