如何从另一个文件渲染异步函数

问题描述 投票:0回答:1

使用 Next.JS。我将为我的 Web 应用程序构建一个管理面板仪表板。为了检索数据库,我使用了 Prisma 客户端MongoDB

我无法显示数据库中的全部用户数。我必须提供数据库中当前所有用户的计数。我尝试渲染在我的 dashboard 页面 上的 db.ts 文件中生成的单独函数,但它不起作用。

代码:-

db.ts

import { PrismaClient } from "@prisma/client";

declare global {
  var prisma: PrismaClient | undefined;
}

export const db = globalThis.prisma || new PrismaClient();

if (process.env.NODE_ENV !== "production") globalThis.prisma = db;

export const userCount = async () => {
  try {
    const count = await db.user.count();
    console.log(count);
    return count;
  } catch (error) {
    console.error("Error counting documents:", error);
    return null;
  }
};

管理/仪表板/page.tsx

"use client";

import { userCount, db } from "@/lib/db";
import { Card, CardHeader, CardContent, CardTitle } from "@/components/ui/card";

const DashboardPage = () => {
  return (
    <Card className="w-full flex-col md:flex">
      <CardHeader>
        <p className="text-2xl font-semibold text-center">Dashboard</p>
      </CardHeader>

      <CardContent className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Users</CardTitle>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="2"
              className="h-4 w-4 text-muted-foreground"
            >
              <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
            </svg>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{userCount()}</div>
            <p className="text-xs text-muted-foreground">
              +20.1% from last month
            </p>
          </CardContent>
        </Card>
      </CardContent>
    </Card>
  );
};

export default DashboardPage;

问题 - 我需要在仪表板页面上呈现用户计数,因此我在 db.ts 中创建了一个名为 userCount 的函数。没有出现。

由于 useEffect 是一个异步函数,我尝试使用它,但它不起作用。它应该显示用户总数。如果我在 db.ts 文件中控制台记录该函数,它会提供计数,但不会显示在 bashboard 页面上。

reactjs mongodb next.js backend
1个回答
0
投票

"use client"
强制你的组件的JS在浏览器中运行,而你无权访问数据库(
userCount()
不会在服务器上运行,然后在客户端上失败)。
只要您不需要该组件中的 JS 交互性,您可以简单地删除该行,它将成为 RSC(React Server Component)。 它将在服务器上运行,并显示正确的值

如果稍后需要添加 JS 交互性(useState、useEffect 等...),那么您可以将组件一分为二:

  • 使用
    userCount()
    并向客户端组件提供 prop 值的 RSC
  • 从其 props 获取
    userCount: number
    的客户端组件,并使用钩子(例如定期更新该值)

请参阅此处更详细的说明(关于 cookie,以及如何在 RSC 和客户端组件之间拆分组件)

© www.soinside.com 2019 - 2024. All rights reserved.