Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

i want to call an api that gives me a json with people and i want to call it and display…

  1. User

    i want to call an api that gives me a json with people and i want to call it and display the data inside a table in next.js

  2. Assistant

    To call an API in Next.js, you can use the built-in Fetch API. Here's an example of how to call the API and display the data in a table:

    1. Create a new file in your Next.js project called "people.js" (or any other relevant name).
    2. Use the following code to fetch the data from the API:
    import React, { useState, useEffect } from "react";
    
    const people = () => {
      const [data, setData] = useState([]);
    
      useEffect(() => {
        const fetchData = async () => {
          const res = await fetch("https://api.url.com/people");
          const jsonData = await res.json();
          setData(jsonData);
        };
        fetchData();
      }, []);
    
      return (
        <div>
          <table>
            <thead>
              <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody>
              {data.map((person, index) => (
                <tr key={index}>
                  <td>{person.name}</td>
                  <td>{person.age}</td>
                  <td>{person.email}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    };
    
    export default people;
    

    Here, we're using the Fetch API to get the data from the API and set it to the "data" state using useState. We're also using useEffect to fetch the data only once when the component mounts.

    1. Import and use the component in your Next.js page. For example, you can create a new page called "peoplePage.js" and use the following code:
    import React from "react";
    import People from "../components/people";
    
    const PeoplePage = () => {
      return (
        <div>
          <h1>People</h1>
          <People />
        </div>
      );
    };
    
    export default PeoplePage;
    

    This will render the "People" component in the "PeoplePage" page, which will display the data in a table. Adjust the URLs and table headers to match your data.