top of page

How to render a table in React from API call

After you've created a clean landing page using React, you might want to start building dynamically rendered pages that load data from a server using an API (if you're lucky, it'll be well-RESTed). This is one of the things that React does very well. Follow the steps below to get started.


1. Set up state for storing data

In your component, set up state to store the data you'll fetch from the API. You can initialize an empty array for the data. For example:


import React, { useState, useEffect } from 'react';

const MyTableComponent = () => {
  const [tableData, setTableData] = useState([]);

  // API call function will be defined later in step 3.
};

2. Use the useEffect hook

The useEffect hook is used to fetch data from the API and update the state. This hook allows you to perform side effects in function components, such as data fetching, subscriptions, or manual DOM manipulation.


import React, { useState, useEffect } from 'react';
import axios from 'axios';

const MyTableComponent = () => {
  const [tableData, setTableData] = useState([]);

  useEffect(() => {
    // Call the API and update the state with the fetched data
    fetchData();
  }, []);

  // API call function will be defined later in step 3.
};

3. Fetch data from API and update state

Create a function that makes the API call using a library like Axios. When the data is received from the API, update the state using setTableData. If you'd like to create your own API, you can use a Node.js framework like Express.


import React, { useState, useEffect } from 'react';
import axios from 'axios';

const MyTableComponent = () => {
  const [tableData, setTableData] = useState([]);

  useEffect(() => {
    // Call the API and update the state with the fetched data
    fetchData();
  }, []);

  const fetchData = () => {
    // Replace 'your-api-endpoint' with the actual API endpoint URL
    axios.get('your-api-endpoint')
      .then(response => {
        // Update the state with the fetched data
        setTableData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  };
};

4. Render the table with the updated data

Use the data stored in the tableData state to render the table in your component's JSX.


import React, { useState, useEffect } from 'react';
import axios from 'axios';

const MyTableComponent = () => {
  const [tableData, setTableData] = useState([]);

  useEffect(() => {
    // Call the API and update the state with the fetched data
    fetchData();
  }, []);

  const fetchData = () => {
    // Replace 'your-api-endpoint' with the actual API endpoint URL
    axios.get('your-api-endpoint')
      .then(response => {
        // Update the state with the fetched data
        setTableData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  };

  return (
    <div>
      <table>
        <thead>
          <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            {/* Add more table headers as needed */}
          </tr>
        </thead>
        <tbody>
          {tableData.map(item => (
            <tr key={item.id}>
              <td>{item.column1}</td>
              <td>{item.column2}</td>
              {/* Add more table data cells as needed */}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

Now, when the component is mounted, the useEffect hook will trigger the fetchData function to make the API call and update the tableData state with the fetched data. The updated data will then be rendered in the table. As a result, whenever the API data changes or the component remounts, the table will automatically update with the latest data.


If you have any questions about React or need a professional software engineer to help with a project you're working on, schedule an intro call with CodeConda for free!

Commentaires


bottom of page