next.js-tutorial

Next.js Api Data Fetching

let’s create a project and create a new file airlines.js and a fake API https://api.instantwebtools.net/v1/airlines.

Open up the directory you’d like to create your project in and run:

npx create-next-app my-airlines-app

After the installation is complete, you can navigate to your new project directory:

cd my-airlines-app

Once there, start your development server:

npm run dev

And once the server is ready, you can open up http://localhost:3000 in your browser where you can now see your new Next.js app!

First of all, let’s make a simple Nextjs page called airlines.js inside our pages folder.

// airlines.js Page
function AirlineList({
  return <h1>Todos</h1>;
};

export default AirlineList;

let’s add the getStaticProps() function.

export default AirlineList;

// add getStaticProps() function
export async function getStaticProps() {}

The getStaticProps() function gives props needed for the component AirlineList to render things when Nextjs builds the page.

Note that we added the async keyword, this is needed so that Nextjs knows to prerender our airlines page at build time.

let’s write some code inside the getStaticProps() function.

// add getStaticProps() function
export async function getStaticProps() {
  const response = await fetch('https://api.instantwebtools.net/v1/airlines')
  const data = await response.json()

  return {
    props: {
      airlines: data
    }
  }
}

  • We can acquire the data for our AirlineList list from an API endpoint or a JSON file, for example.
  • Like way, we should return the airlines array from the props object.
return {
    props: {
      airlines: data
    }
};

Now let’s complete our AirlineList render code.

airlines.js

function AirlineList({
  airlines
}) {
  return (
    <>
      <h1> List of Airlines </h1> {
      airlines.map(airline => {
        return (
          <div key = {airline.id} >
            <p> {airline.name} </p>
            <p> {airline.country} </p>
            <p> {airline.slogan} </p>
          </div>
        )
      })
    } <
    />
  )
}

export default AirlineList

export async function getStaticProps() {
  const response = await fetch('https://api.instantwebtools.net/v1/airlines')
  const data = await response.json()

  return {
    props: {
      airlines: data
    }
  }
}

We are just mapping over our AirlineList array we received as a prop and rendering each airlines from the array inside an unordered list using the map() function in JavaScript.

The airlines prop is returned from getStaticProps() function.

Now run the app and navigate to http://localhost:3000/airlines.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.