API Integration
One of our major update this year includes API Integration. A function that runs on the server and returns mock data.
Let’s look at one example:
import { getDevicesUsedData } from "@/services/charts.services";
const data = await getDevicesUsedData(timeFrame);
An asynchronous function, which is placed in a separate file for better separation of concerns. It returns mock data for demo purposes. However, as you might have guessed, in this function you can include your own business logic for returning data.
You can fetch data from an external API or make database call directly within the function. In Next15 we are leveraging the full potential of RSC, so you can safely make database call within the function as long as you invoke the function in a server component.
If you go to the function definition you’ll find something similar:
export async function getDevicesUsedData(
timeFrame?: "monthly" | "yearly" | (string & {}),
) {
// Fake delay
await new Promise((resolve) => setTimeout(resolve, 1000));
const data = [
{
name: "Desktop",
percentage: 0.65,
amount: 1625,
},
{
name: "Tablet",
percentage: 0.1,
amount: 250,
},
// ...rest
];
if (timeFrame === "yearly") {
data[0].amount = 19500;
data[1].amount = 3000;
}
return data;
}
Notice the comment for Fake delay, we are using it to simulate network request delay so the data does not return from the immediately after invocation. In this way we can also show loading skeleton.
Loading skeleton
As we covered before, our API integration includes fake delay to simulate network request. Which introduces the scope for showing loading skeletons.
Most of the components in this update that has API integration has loading skeleton file.
Let’s look at the top-channels component on the home page:
import { Suspense } from "react";
import { TopChannels } from "./_components/top-channels";
import { TopChannelsSkeleton } from "./_components/top-channels/skeleton";
<Suspense fallback={<TopChannelsSkeleton />}>
<TopChannels />
</Suspense>;
The component is wrapped in a Suspense boundary with a fallback skeleton component. This means while the data is being fetched (simulated by the fake delay), the skeleton will be shown to provide visual feedback to users.
The skeleton component typically mimics the structure of the actual component but with placeholder animations to indicate loading state.
Here's what happens when this code runs:
- The Suspense boundary is rendered with the
TopChannels
component - When
TopChannels
starts fetching data, it suspends - The
TopChannelsSkeleton
is shown while data is being fetched - Once data is available,
TopChannels
replaces the skeleton
This pattern provides a better user experience by avoiding jarring empty states and layout shifts.
In our source code, we are using this approach in most places so you can get a demonstration on how to use this pattern effectively.
We’re very excited to share this update with you, it opens the door for scaling the application in new heights.