Home > database >  How to render total number of objects in array react
How to render total number of objects in array react

Time:11-05

Just wondering how can I go about, rendering the total length of the this.state.apiData array on the output screen. so I can go on and use conditional formatting with the outputted results.

that the user can see the total number of stock objects returned. T

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    // create three state variables.
    // apiData is an array to hold our JSON data
    // isFetched indicates if the API call has finished
    // errorMsg is either null (none) or there is some error
    this.state = {
      apiData: [],
      isFetched: false,
      errorMsg: null
    };
  }
  // componentDidMount() is invoked immediately after a
  // component is mounted (inserted into the tree)

  async componentDidMount() {
    try {
      const API_URL =
        "#";
      // Fetch or access the service at the API_URL address
      const response = await fetch(API_URL);
      // wait for the response. When it arrives, store the JSON version
      // of the response in this variable.
      const jsonResult = await response.json();

      // update the state variables correctly.
      this.setState({ apiData: jsonResult.stockData });
      this.setState({ isFetched: true });
    } catch (error) {
      // In the case of an error ...
      this.setState({ isFetched: false });
      // This will be used to display error message.
      this.setState({ errorMsg: error });
    } // end of try catch
  } // end of componentDidMount()

  // Remember our three state variables.
  // PAY ATTENTION to the JSON returned. We need to be able to
  // access specific properties from the JSON returned.
  // Notice that this time we have three possible returns for our
  // render. This is conditional rendering based on some conditions
  render() {
    if (this.state.errorMsg) {
      return (
        <div className="error">
          <h1>We're very sorry: An error has occured in the API call</h1>

          <p>The error message is: {this.state.errorMsg.toString()}</p>
        </div>
      ); // end of return.
    } else if (this.state.isFetched === false) {
      return (
        <div className="fetching">
          <h1>We are loading your API request........</h1>
          <p>Your data will be here very soon....</p>
        </div>
      ); // end of return
    } else {
      // we have no errors and we have data
      return (
        <div className="App">
          <div className="StocksTable">
            <h1>CS385 - Stocks API Display</h1>
            <table border="1">
              <thead>
                <tr>
                  <th>stock ID</th>
                  <th>Industry</th>
                  <th>Sector</th>
                  <th>Symbol</th>
                  <th>Name</th>
                  <th>Buy</th>
                  <th>Sell</th>
                  <th>Timestamp</th>
                </tr>
              </thead>
              <tbody>
                {this.state.apiData.map((s) => (
                  <tr>
                    <td>{s.StockID}</td>
                    <td>{s.stock.industry}</td>
                    <td>{s.stock.sector}</td>
                    <td>{s.stock.symbol}</td>
                    <td>{s.stock.name}</td>
                    <td>{s.rates.buy}</td>
                    <td>{s.rates.sell}</td>
                    <td>{s.rates.timestamp}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ); // end of return
    } // end of the else statement.
  } // end of render()
} // end of App class
export default App;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Here is an example of one of my array objects:

{"stockData":
  [
    {
      "stockID":1,
      "stock":
      {
        "industry":"Investment Bankers/Brokers/Service",
        "sector":"Finance",
        "symbol":"JMP",
        "name":"JMP Group LLC"
        },
        "rates":
        {
          "buy":12.6,
          "sell":393.11,
          "timestamp":"2024-06-05 19:12:01"
          }
        },
{
  "stockID":2,
  "stock":
  {
    "industry":"Investment Bankers/Brokers/Service",
    "sector":"Finance",
    "symbol":"USOI",
    "name":"Credit Suisse AG"
    },
    "rates":
    {
      "buy":363.49,
      "sell":14.15,
      "timestamp":"2024-08-30 13:37:23"
      }
    },
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Thanks!

CodePudding user response:

It is a simple as:

<div>{this.state.apiData.length}</div>

CodePudding user response:

Maybe the size property would help with that ?

So probably something like :

let objAmount = this.state.apiData.size

Or even just

this.state.apiData.size

, if you don't want to use a variable.

  • Related