Define an API function: Create a file inside the api directory, e.g., api.ts, to define the API function. This function should handle making the actual API request using a library like axios or the built-in fetch function. It can use the async/await syntax for handling asynchronous requests.
import axios from 'axios';
const apiUrl = 'https://api.example.com';
export const fetchData = async (params: any) => {
try {
const response = await axios.get(`${apiUrl}/your-endpoint`, { params });
return response.data;
} catch (error) {
console.error('API Error:', error);
throw error;
}
};
Handle API calls in Next.js pages: In your Next.js pages, import the API function you defined and call it as needed. You can use either the getStaticProps or getServerSideProps methods for server-side rendering, or use useEffect and useState for client-side rendering.
a. Server-side rendering (Static Generation):
import { GetStaticProps } from 'next';
import { fetchData } from '../api/api';
const MyPage = ({ data }: { data: any }) => {
// Use the fetched data here
return <div>{data}</div>;
};
export const getStaticProps: GetStaticProps = async () => {
const data = await fetchData({ param1: 'value1' });
return {
props: {
data,
},
};
};
export default MyPage;
b. Server-side rendering (Server-side Rendering):
import { GetServerSideProps } from 'next';
import { fetchData } from '../api/api';
const MyPage = ({ data }: { data: any }) => {
// Use the fetched data here
return <div>{data}</div>;
};
export const getServerSideProps: GetServerSideProps = async () => {
const data = await fetchData({ param1: 'value1' });
return {
props: {
data,
},
};
};
export default MyPage;
c. Client-side rendering:
import { useEffect, useState } from 'react';
import { fetchData } from '../api/api';
const MyPage = () => {
const [data, setData] = useState<any>(null);
useEffect(() => {
const fetchDataAsync = async () => {
try {
const result = await fetchData({ param1: 'value1' });
setData(result);
} catch (error) {
console.error(error);
}
};
fetchDataAsync();
}, []);
// Use the fetched data here
return <div>{data}</div>;
};
export default MyPage;