Home > other >  how to display nested items using fetchData method in react.js
how to display nested items using fetchData method in react.js

Time:02-08

I'm able to fetch the data but not sure how to map nested items data looks like that

{"id":3,
      "brands":[{"id":6,"products":[],    
                 "title":"Lenovo",
                 "image":"/img.png",
                 "timestamp":"2022-02-07T15:11:36.059719 05:30",
                 "updated":"2022-02-07T15:11:36.059719 05:30",
                 "category":3}],
"title":"Laptop",
"image":"/img.png",
"timestamp":"2022-01-30T23:18:14.124583 05:30",
"updated":"2022-01-30T23:18:14.124583 05:30"}

I'm using following method to do this.

const CategoriesToBrands = ({ match }) => {
  const [hasError, setErrors] = useState(false);
  const [items, setItems] = useState({});
  const { id } = useParams();
  async function fetchData() {
    const data  = await fetch("/api/v1/categories/nested/"   id);
    data.json()
      .then(data => setItems(data))
      .catch(data => setErrors(data));
  }
  useEffect(() => {
    fetchData()
  }, [])

  return (
    <div>
      <div>{JSON.stringify(items)}</div>
      <hr />
        {items.title}
      <hr />
      <div>Has error: {JSON.stringify(hasError)}</div>
    </div>
  );
};
export default CategoriesToBrands;

I also tried multiple method suggested on stack overflow to map the items but no one seems to be working . or they are using another method . there can be multiple number of items in brands [] and i want to display each one of them for now there is one.. So what would be the syntax or method to map them properly.

CodePudding user response:

You have an brands array inside your main object fetched by async request. It means you should to get brands by items.brands. Something like that:

const CategoriesToBrands = ({ match }) => {
  const [hasError, setErrors] = useState(false);
  const [items, setItems] = useState({});
  const { id } = useParams();
  async function fetchData() {
    const data  = await fetch("/api/v1/categories/nested/"   id);
    data.json()
      .then(data => setItems(data))
      .catch(data => setErrors(data));
  }
  useEffect(() => {
    fetchData()
  }, [])

  return (
    <div>
      <div>{JSON.stringify(items)}</div>
      <hr />
        {items.title}
      <hr />
      {items.brands ? items.brands.map(brand => (
         <div key={brand.id}>brand id: {brand.id}</div>
      )) : null}
      <div>Has error: {JSON.stringify(hasError)}</div>
    </div>
  );
};
export default CategoriesToBrands;

The good idea is also changing the name of your const [items, setItems] = useState({});. In your case you are fetching one item, not multiple (I assume this fact by your id variable). So the name like item, setItem sounds better.

  •  Tags:  
  • Related