[next.js  개발] How to use fetch API in Next.js?

 

JavaScript is extensively used in almost all the fields of Computer Sciences. One of its areas of use is the Web, where it utilizes browser APIs to support dynamic websites. JavaScript also offers a wide variety of frameworks and libraries to help the coding process easier, simpler, and more efficient.

In this piece, we will look at how to use the fetch API in Next.js. So without any further ado, let’s jump in!

Next.js

​​It is a web framework built on top of React.js. Next.js extends the capabilities of React.js by providing the developers with features like server-side rendering, static site generation, incremental static generation, a working REST API, file-system-based routing, dynamic routing, etc. It provides better optimization, additional structure, and features to your application.

Since it extends React.js, you can start by writing all the React.js code and eventually add Next.js features to your application. You can render the application server-side, so all the data has been pre-fetched before loading the web app in the browser. Afterward, you can write a simple REST API without setting up a Node.js server.

Use fetch API

Let’s do it in steps to make things simpler.

→ STEP #1

We need an API that we can call to learn how to use the fetch API in Next.js. For this, we will use RapidAPI Hub, which provides over 35,000+ APIs.

We will use the Famous Quotes API from RapidAPI Hub, so please go ahead and subscribe to it.

→ STEP #2

Now we need to set up a Next.js application. The simplest way to do it is by running the following command in your terminal:

 
SH
npx create-next-app next-app

The command will create a Next.js project called next-app. If you want to change the name, you can just replace next-app with what you want.

→ STEP #3

Now open this directory in your preferred code editor. Afterward, run the application running the following command in your project terminal:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 
SH
npm run dev

It will start the development environment of your Next.js application.

→ STEP #4

Once you are done, open the index.js file inside the pages directory and delete all the code. Now copy and paste the following inside this file:

 
JS
import styles from '../styles/Home.module.css';
 
export default function Home() {
const callAPI = async () => {};
return (
<div className={styles.container}>
<main className={styles.main}>
<button onClick={callAPI}>Make API call</button>
</main>
</div>
);
}

The above code will render a button that will execute callAPI function when clicked.

We will use our fetch API inside the callAPI function to call APIs. Let’s learn how to do this.

 
JS
const callAPI = async () => {
try {
const res = await fetch(
`https://famous-quotes4.p.rapidapi.com/random?category=all&count=2`,
{
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com',
},
}
);
const data = await res.json();
console.log(data);
} catch (err) {
console.log(err);
}
};

The fetch API is asynchronous, so we need to await it. It is a function that takes the API endpoint as its first parameter. The second parameter of the fetch API is an object that contains data like HTTP method, request headers, request body, etc.

We have made a GET request in the above code snippet. If you want to make a POST request, you can just replace GET with POST. Here is a sample code snippet of how you can make a POST request using fetch API in Next.js.

 
JS
const res = await fetch(`API-ENDPOINT`, {
method: 'POST',
body: {},
});
const data = await res.json();
console.log(data);

You can see that the method is POST with a body key holding an object. This object will contain the request body that is sent along with a POST API request.

Here is the final code that you can just copy and paste into your index.js file:

 
JS
import styles from '../styles/Home.module.css';
 
export default function Home() {
const callAPI = async () => {
try {
const res = await fetch(
`https://famous-quotes4.p.rapidapi.com/random?category=all&count=2`,
{
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com',
},
}
);
const data = await res.json();
console.log(data);
} catch (err) {
console.log(err);
}
};
 
return (
<div className={styles.container}>
<main className={styles.main}>
<button onClick={callAPI}>Make API call</button>
</main>
</div>
);
}

We are calling the callAPI function on the onClick event handler of the button. It makes an API call using fetch API in a Next.js app.

Wrap Up

That’s all, folks! I hope you now understand how to use the fetch API inside the Next.js app to call other APIs.

[출처] https://rapidapi.com/guides/how-to-use-fetch-api-in-next-js

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
523 [node.js 개발] PM2를 활용한 Node.js 무중단 서비스하기 file 졸리운_곰 2024.03.16 517
522 [Next.js 개발] NextAuth.js 를 이용한 자체 로그인 구현 졸리운_곰 2024.03.09 560
521 [Next.js 개발] Using Next.js Version 13 file 졸리운_곰 2024.03.09 409
520 [Next.js 개발] Common Errors in Next.js and How to Resolve Them file 졸리운_곰 2024.03.09 468
519 [Next.js 개발] [Javascript] 현재 날짜, 시간 구하기 졸리운_곰 2024.03.09 430
518 [microfrontend][마이크로프론트엔드] 마이크로프론트엔드 아키텍쳐 file 졸리운_곰 2024.03.08 574
517 [microfrontend][마이크로프론트앤드] Building Micro Frontends With React : React로 마이크로 프론트엔드 구축 file 졸리운_곰 2024.03.08 536
516 [Next.js 개발] Using Next.js Version 13 : Next.js 버전 13 사용 file 졸리운_곰 2024.03.07 499
515 [Next.js 개발] [React] useEffect에서 async/await file 졸리운_곰 2024.03.06 362
» [next.js 개발] How to use fetch API in Next.js? file 졸리운_곰 2024.03.05 368
513 [next.js 개발] Next.js14에 Mysql연결하기 졸리운_곰 2024.03.05 457
512 [next.js 개발] How To Connect MySQL And Auth To A Next.js App file 졸리운_곰 2024.03.05 323
511 [next.js 개발] Next.js 소개와 14 버전 변경사항 – React 인기 라이브러리 file 졸리운_곰 2024.03.05 523
510 [next.js 개발] next.js API 호출시 - 수신부따로 호출하고 await 붙일것 졸리운_곰 2024.03.05 555
509 [next.js 개발] [Next.js] Fetch POST body에 json 형태로 데이터 주고받기 (json형 / object형 차이) 졸리운_곰 2024.03.05 456
508 [node.js 응용] Next.js : Next.js14에 Mysql연결하기 졸리운_곰 2024.03.03 379
507 [JavaScript] lastIndexOf() : String에서 원하는 값의 마지막 위치(index) 찾기 졸리운_곰 2024.02.28 366
506 [JS] 문자열의 위치 찾기 & 문자열 추출하기 file 졸리운_곰 2024.02.28 573
505 [JavaScript] lastIndexOf() : String에서 원하는 값의 마지막 위치(index) 찾기 졸리운_곰 2024.02.28 544
504 [node.js 응용] Node.js에서 다른 파일의 함수를 "include" 하는 방법 졸리운_곰 2024.02.28 427
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED