DevX
DevX

Reputation: 541

React data isn't being displayed

I'm trying to display these data that is stored in countries list, however, it is result in me getting nothing in my Table. The problem is most likely caused by the Table not rerendering correctly, I tried to use useEffect on line 14 to print out the length of the list, and I did get the correct result. Any hint would be appreciated!

import React, { useState, useEffect } from "react";
import getData from "../Hooks/getData";
import Table from "react-bootstrap/Table";

const Lists = () => {
  const [countries, setCountries] = useState([]);

  if (countries.length === 0) {
    getData().then((data) => {
      setCountries(data.data.Countries);
    });
  }

  useEffect(() => {
    console.log(countries.length);
  });

  const getInfo = () => {
    countries.map((country) => {
      return (
        <tr>
          <td>{country.Country}</td>
          <td>{country.NewConfirmed}</td>
          <td>{country.TotalConfirmed}</td>
        </tr>
      );
    });
  };

  return (
    <Table striped bordered hover>
      <thead>
        <tr>
          <th>Country Name</th>
          <th>New Confirmed</th>
          <th>Total Confirmed</th>
        </tr>
      </thead>
      <tbody>{getInfo()}</tbody>
    </Table>
  );
};

export default Lists;

Upvotes: 1

Views: 42

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

Your getInfo does not return anything.

Either use the implicit return, by not using {} around the funtion body, or explicitly use the return statement

 const getInfo = () => countries.map((country) => {
      return (
        <tr>
          <td>{country.Country}</td>
          <td>{country.NewConfirmed}</td>
          <td>{country.TotalConfirmed}</td>
        </tr>
      );
    });

or

  const getInfo = () => {
    return countries.map((country) => {
      return (
        <tr>
          <td>{country.Country}</td>
          <td>{country.NewConfirmed}</td>
          <td>{country.TotalConfirmed}</td>
        </tr>
      );
    });
  };

Upvotes: 3

Related Questions