I've been trying to understand what's the proper way to call an external API from a Next.js application, because I'm used to developing MERN stack apps, I usually use axios for my API calls and use that inside a useEffect. Trying to learn Next.js and with all the information to take in, I got confused, especially with server components and whatnot, I tried doing the following and it seems to work but the question is: is it really the proper way?
my-next-app>app>api>hello>route.ts
import axios from "axios";
export async function GET() {
const response = await axios.get("http://localhost:5000");
return Response.json(response.data);
}
my-next-app>hello>page.tsx
"use client";
import axios from "axios";
import * as React from "react";
export default function page() {
const [msg, setMsg] = React.useState("");
React.useEffect(() => {
axios.get("api/hello").then((res) => {
// { msg: "Hello World!" }
setMsg(res.data.msg);
});
}, []);
return <div>{msg}</div>;
}