Leveraging React Hooks and Axios for retrieving data and showcasing it in a table

I have set up a React environment, created a hook named ApiTable, and implemented a method called renderTable. My goal is to fetch data from the API endpoint located at

https://jsonplaceholder.typicode.com/users
, and display it in a table with the appropriate categories.

Currently, all the columns are being squished together on the left side. The data isn't displaying correctly and appears compressed on the left side. I suspect there might be an issue with how I structured the table data.

Furthermore, I'm uncertain whether the axios request should be placed inside the useEffect or not.

https://imgur.com/a/Up4a56v


const ApiTable = () => {

  const url = 'https://jsonplaceholder.typicode.com/users';

  const [data, setData] = useState([]);

  useEffect(() => {

    setData([data]);

    axios.get(url)
    
    .then(json => console.log(json))

  }, []);

  const renderTable = () => {

      return data.map((user) => {

        const { name, email, address, company } = user;

        return (
          <div>
           <thead>
               <tr>
                 <th>Name</th>
                 <th>Email</th>
                 <th>Address</th>
                 <th>Company</th>
               </tr>
          </thead>
          <tbody>
          <tr>
              <td>name</td>
              <td>email</td>
              <td>address</td>
              <td>company</td>
          </tr>
          </tbody>
          </div>
        )
      })
    }


      return (
        <div>
            <h1 id='title'>API Table</h1>
            <Table id='users'>
              {renderTable()}
            </Table>
         </div>
      )

};
      

Answer №1

Your data fetching method is correct, but the way you are setting the data to state is incorrect.

Additionally, when iterating through your data array, you are displaying the table head with each iteration, which is not the intended behavior. Also, keep in mind that the address and company properties in your data array are objects, so they cannot be directly printed.

To resolve this issue, make the following adjustments:

const App = () => {
  const url = 'https://jsonplaceholder.typicode.com/users'

  const [data, setData] = useState([])

  useEffect(() => {
    axios.get(url).then(json => setData(json.data))
  }, [])

  const renderTable = () => {
    return data.map(user => {
      return (
        <tr>
          <td>{user.name}</td>
          <td>{user.email}</td>
          <td>{user.address.street}</td> //Showing only street name, iterate over `user.address` object for complete address
          <td>{user.company.name}</td> //Displaying only company name, iterate over `user.company` object for full details
        </tr>
      )
    })
  }

  return (
    <div>
      <h1 id="title">API Table</h1>
      <table id="users"> //Changed from post's Table to table for functionality
        <thead>
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Address</th>
            <th>Company</th>
          </tr>
        </thead>
        <tbody>{renderTable()}</tbody>
      </table>
    </div>
  )
}

Check out the Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Have you ever wondered why JSON organizes data objects in the format {"city":[{"com.getcity.@FAE87A"}]

String city = request.getParameter("name1"); HttpSession session = request.getSession(); try { ConnectToDb db = new ConnectToDb(); con =db.getConnect(); pstmt = con.prepareStatement("select Name, CountryCode, District, Population from city whe ...

Implement a line break for each iteration in jQuery's each function

I've been grappling with an issue for some time now. I have a search box that triggers a GET method using php+mysql+jquery+json. Upon receiving the json result, I display it on the DOM. The problem lies in how I'm displaying the results: success ...

Error encountered in jQuery call during Page_Load

Here is the code I am using to register a javascript function on Page_Load (I also tried it on Page_Init). This javascript function switches two panels from hidden to shown based on a parameter when the page loads: protected void Page_Load(object sen ...

What is the best way to display a loading screen while awaiting the rendering process in ReactJS?

Recently, I created a CSS-animated "loading" element for my web page. However, I want it to only be visible when data is being loaded or rendered. Do you have any suggestions? I'm quite new to this and could use some guidance. This is how I implement ...

Validating complex ASP.NET MVC objects using AngularJS

I am encountering an issue with validating my model in a subform using AngularJS. Despite making changes to the SearchPostCode values and seeing updates in classes, the error message fails to display, and the button remains disabled. <form novalidate&g ...

Enzyme's simulate() failing to produce expected results with onChange event

I am facing an issue with a component and its related tests: import React from 'react'; import PropTypes from 'prop-types'; function SubList (props) { var subways = ['', '1', '2', '3', & ...

Is it possible to incorporate a timer script like chrontab within an Apache setting?

Is it possible to create a chronTab that runs a php script on an Apache web server (Unix based systems) in conjunction with the Node.js server-side program? My goal is to use this to check if a browser is still active and when to end sessions. The chronTa ...

Creating background color animations with Jquery hover

<div class="post_each"> <h1 class="post_title">Single Room Apartments</h1> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb last" ...

Comparing Jquery ajax object in Internet Explorer is not possible

Currently, I am utilizing jQuery's ajax function to fetch an HTML page. Upon success, a data object is retrieved. I aim to compare this data object to a string to determine the necessary actions. This functionality performs as expected in Firefox and ...

In Bootstrap 5, clicking inside a dropdown should not cause it to open or close unexpectedly

Check out the code snippet below: <html> <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f1212090e090f1c0d3d48534e534e">[email protected]</a>/d ...

Dealing with functions that may not consistently return a promise

When dealing with a situation where a function does not always return a promise, how can it be best handled? The complexity of my current code prevents me from providing a detailed explanation, but essentially, the issue involves checking a condition and t ...

Displaying a portion of a React functional component once an asynchronous function call has been successfully executed

I am currently using material-ui within a React function component and have implemented its Autocomplete feature. I have customized it so that when the text in the input field changes, I expect the component to display new search results. callAPI("xyz") I ...

Error: Unexpected character found at line 1, position 2 in the JSON data caused a syntax error when parsing

When trying to append this div to another div, I encountered the following error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data This snippet shows my JavaScript code: var str = {'message': message,' ...

How can you properly structure chainable functions in Angular?

Recently, I've been working on developing custom functions for my Angular application. Following the official guidelines, I have created an independent library. My goal is to create chainable functions similar to this: var obj = { test : function( ...

The outcome of AES encryption varies when comparing Node JS with C# programming languages

In a particular scenario, I need to encrypt and transmit text using the AES 256 algorithm. The decryption process will be handled by client-side C# code. Here is the encryption code in JavaScript: const crypto = require('crypto'); algorithm = ...

Leverage the power of Meteor by incorporating templates to dynamically inject HTML based on an event

I am currently generating HTML using JQuery on an event. However, I believe a better approach would be to use templates in Meteor, especially if the HTML becomes more complex. Template.example.onRendered(function() { paper.on({ 'cell:mous ...

The $or operator in mongoose falls short in providing complete data when paired with the find() method

I am currently utilizing the find method in conjunction with the $or operator to search the database for any duplicate data within this specific line. const duplicate = await NewItemsData.find({ $or: newItems }); Upon inspecting the variable in the consol ...

setting the minimum date for a datepicker

Does anyone know how to set the minimum date for a calendar to be 2 days from the current date? For example, if today is the 27th, the minimum date should be the 29th. Any suggestions? Thanks. https://i.sstatic.net/7yHhH.png #html code <mat-form-field ...

Tips for importing HTML modules using AJAX technology?

Is it possible to load the correct module on my site depending on the path that the user enters? Would storing the HTML in a file named some_file.htm, ajaxing that file to the client, and then appending it to the DOM work for this purpose? I'm curio ...

Display a fixed legend on Google Chart without showing percentage values

<script type="text/javascript"> // Loading the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Setting a callback to run when the Goo ...