Blog>
Snippets

Fetching Data with Axios

Show how to use Axios, a promise-based HTTP client, for making API requests from a Next.js page or an API route.
import axios from 'axios';

export async function getServerSideProps(context) {
  // Fetch data from an API endpoint
  const res = await axios.get('https://api.example.com/data');
  const data = res.data;

  // Pass data to the page via props
  return { props: { data } };
}

function Page({ data }) {
  // Render data in the page
  return (
    <div>
      <h1>Data Fetched with Axios</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default Page;
This JavaScript code uses Axios to fetch data from an API endpoint in a Next.js page's `getServerSideProps` function. The fetched data is passed as props to the page component which renders it.
import axios from 'axios';

export default async function handler(req, res) {
  try {
    // Fetch data from an external API endpoint
    const response = await axios.get('https://api.example.com/data');
    // Send the fetched data back as a response
    res.status(200).json(response.data);
  } catch (error) {
    // Handle any errors
    res.status(500).json({ message: 'An error occurred', error });
  }
}
This JavaScript code represents an API route in Next.js which uses Axios to fetch data from an external API and sends it back as a response to the client.
import axios from 'axios';
import { useState, useEffect } from 'react';

function FetchDataComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Fetch data when the component mounts
    axios.get('https://api.example.com/data')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('There was an error fetching the data', error);
      });
  }, []);

  return (
    <div>
      <h1>Data Fetched with Axios</h1>
      <pre>{data ? JSON.stringify(data, null, 2) : 'Loading...'}</pre>
    </div>
  );
}

export default FetchDataComponent;
This JavaScript code defines a React functional component that uses Axios to fetch data from an API when the component mounts. The data is maintained in the component's local state and rendered.