[Next.js] Consume Next.js API routes with the SWR library on the client-side

The cool thing about Next.js API routes is that we can directly consume the API endpoints from pages.

SWR is a nice tool for handling data loading state in React apps using hooks, and is a perfect companion for our Next.js application. In this lesson, we will learn how to use SWR - a data fetching library by Zeit - to consume API endpoints on the client-side, and conditionally render an error or a loading component when the data is not available.

 

pages/api/user/[id].ts:

复制代码
import { NextApiHandler } from "next";

const data = [
  { id: 1, name: "Wan" },
  { id: 2, name: "Zhen" },
  { id: 3, name: "Tian" }
];

const user: NextApiHandler = (req, res) => {
  const { id } = req.query;
  const userData = data.find(x => String(x.id) === String(id));

  if (userData) {
    res.status(200).json(userData);
  } else {
    res.status(404).end();
  }
};

export default user;
复制代码

 

pages/user/[id].tsx:

复制代码
import { useRouter } from "next/router";
import { SimpleGrid, Text, Alert, Flex, Heading } from "@chakra-ui/core";
import useSWR from "swr";

const fetcher = async (url: string) => {
  const res = await fetch(url);
  if (!res.ok) {
    throw Error("Yo that's NOT OK!!!");
  }
  const data: {
    id: string;
    name: string;
    email: string;
  } = await res.json();

  return data;
};

const UserData = () => {
  const router = useRouter();
  const { id } = router.query;
  const { data, error } = useSWR(`/api/user/${id}`, fetcher);

  if (error) {
    return <Alert status="error">Loading fail</Alert>;
  }

  if (!data) {
    return <Alert status="info">Loading...</Alert>;
  }

  return (
    <SimpleGrid columns={2} width="2xs" spacingY={4}>
      <Text fontWeight="bold" marginRight={4}>
        UserID
      </Text>
      <Text>{data.id}</Text>

      <Text fontWeight="bold" marginRight={4}>
        Name
      </Text>
      <Text>{data.name}</Text>

      <Text fontWeight="bold" marginRight={4}>
        Email
      </Text>
      <Text>{data.email}</Text>
    </SimpleGrid>
  );
};

const user = () => {
  return (
    <Flex flexDirection="column" alignItems="center">
      <Heading as="h1">User</Heading>
      <UserData />
    </Flex>
  );
};

export default user;
复制代码

 

posted @   Zhentiw  阅读(460)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-04-03 [Spring Boot] @Component, @AutoWired and @Primary
2019-04-03 [Algorithm] Find merge point of two linked list
2019-04-03 [Docker] Linking Node.js and MongoDB Containers
2018-04-03 [GraphQL] Fetch Server Data and Client-side State in One Query using React Apollo + GraphQL
2018-04-03 [Angular] Getting to Know the @Attribute Decorator in Angular
2016-04-03 [Angular 2] Async Http
点击右上角即可分享
微信分享提示