Home > front end >  React JSON object unpacking correctly and show it on UI
React JSON object unpacking correctly and show it on UI

Time:06-24

I was able to successfully get API call and receive the JSON object. However, I do not think I am unpacking the objects properly after put it on my array.

this is the json object I received and saved in the array:

enter image description here

import React, { useState, useEffect } from "react";
import APIService from "./APIService";

export default function BeerComponent() {
  const [beers, setBeers] = useState([]);

  function buttoncomponentDidMount() {
    APIService.getBeers()
      .then((response) => response.json())
      .then((data) => {
        //console.log(data);
        setBeers(data);
        console.log(beers);
      })
      .catch(function (ex) {
        console.log(ex);
        console.log("Response parsing failed. Error: ", ex);
      });
  }

  return (
    <div>
      <button onClick={buttoncomponentDidMount}>Beer Button</button>
      <h2 className="text-center">Beer Details</h2>
      <table className="table table-striped">
        <thead>
          <tr>
            <th>Beer Id</th>
            <th>Beer Name</th>
            <th>{beers &&
              beers.length > 0 &&
              beers.map((item) => <p>{item.beerCompanyName}</p>)}
              </th>
          </tr>
        </thead>
        <tbody></tbody>
        {/* <tbody>
                        {
                            beers.map(beer =>
                                    <tr key={beer.userId}>
                                        <td>{beer.id}</td>
                                        <td>{beer.title}</td>
                                    </tr>
                            )
                        }
                    </tbody> */}
      </table>
    </div>
  );
}


CodePudding user response:

It looks like your API is returning you an object which has a property called beers, which is the array of beers:

{
  "beers": [
    { "beerCompanyName": "Just the best beer", ... },
    { "beerCompanyName": "Just the best beer", ... },
    { "beerCompanyName": "Just the best beer", ... }
  ]
}

So you'd need to put the beers property into your state object:

APIService.getBeers()
  .then((response) => response.json())
  .then((data) => {
    setBeers(data.beers);    // Add '.beers' here
  })
  • Related