Next.js is a framework built on React that provides capabilities for building Server-Side Rendering (SSR) and static websites. It also supports executing data API requests on the client-side. This is typically done within component lifecycle methods or using React Hooks. Here are some common methods for performing data API requests on the client-side:
Using fetch API
Within the component, you can use the native fetch API to perform data requests. For example:
jsximport React, { useEffect, useState } from 'react'; const MyComponent = () => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); }; fetchData(); }, []); // Empty array indicates this effect runs only once when the component mounts if (!data) return <div>Loading...</div>; return <div>{JSON.stringify(data)}</div>; }; export default MyComponent;
Using axios
axios is a popular HTTP client library that offers richer configuration options and features. You need to install it first, then use it within the component:
jsximport React, { useEffect, useState } from 'react'; import axios from 'axios'; const MyComponent = () => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { const response = await axios('https://api.example.com/data'); setData(response.data); }; fetchData(); }, []); if (!data) return <div>Loading...</div>; return <div>{JSON.stringify(data)}</div>; }; export default MyComponent;
Using SWR
SWR is a React Hooks library provided by Vercel (the developer of Next.js) for data fetching. It offers many useful features, such as automatic revalidation, cache control, and focus revalidation.
First, install SWR:
bashnpm install swr
Then use it within the component:
jsximport useSWR from 'swr'; import React from 'react'; const fetcher = (...args) => fetch(...args).then(res => res.json()); const MyComponent = () => { const { data, error } = useSWR('https://api.example.com/data', fetcher); if (error) return <div>Failed to load</div>; if (!data) return <div>Loading...</div>; return <div>{JSON.stringify(data)}</div>; }; export default MyComponent;
These methods are executed on the client-side, so they do not participate in Next.js's Server-Side Rendering or Static Generation processes. If you need to fetch data on the server-side to leverage the benefits of SSR or SSG, you should fetch data within the appropriate Next.js lifecycle methods, such as getStaticProps or getServerSideProps.