嗨, 我想在下一个 js 中使用 React 查询,但出现一些错误。 我有一个我创建的自定义钩子:
import { useMutation, useQuery } from "@tanstack/react-query";
import { auth } from "@clerk/nextjs/server";
import { User } from "@prisma/client";
const { getToken, userId } = auth();
type CreateUserParams = {
name: string;
email: string;
};
export function useCreateUsers() {
const CreateUserFunction = async ({
newUser,
}: {
newUser: CreateUserParams;
}) => {
try {
const data = await fetch("http://localhost:3000/api/prisma/users", {
method: "POST",
headers: {
Authorization: `Bearer ${await getToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(newUser),
});
const user = await data.json();
return user;
} catch (error) {
console.error(error);
return new Error("An error occurred");
}
};
const { mutate, isPending, isError, error, data } = useMutation({
mutationKey: ["createUser"],
mutationFn: CreateUserFunction,
});
return { mutate, isPending, isError, error, data };
}
我尝试在另一个客户端组件中使用它,如下所示:
const { mutate, isPending, isError, error } = useCreateUsers();
但我收到此错误:
'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.
我尝试在服务器组件中使用此自定义挂钩,但它也不起作用
你必须区分你的API逻辑和自定义钩子,这样你才能在客户端组件中使用钩子,而在服务器组件中使用API逻辑。
// pages/api/users/user.js
import { auth } from "@clerk/nextjs/server";
import prisma from "../../../lib/prisma"; // Adjust the import path as needed
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ message: "Method not allowed" });
}
try {
const { userId } = auth();
if (!userId) {
return res.status(401).json({ message: "Unauthorized" });
}
const { name, email } = req.body;
const user = await prisma.user.create({
data: { name, email },
});
res.status(201).json(user);
} catch (error) {
console.error(error);
res.status(500).json({ message: "An error occurred" });
}
}
import { useMutation } from "@tanstack/react-query";
type CreateUserParams = {
name: string;
email: string;
};
export function useCreateUsers() {
const createUserFunction = async (newUser: CreateUserParams) => {
const response = await fetch("/api/users/create", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newUser),
});
if (!response.ok) {
throw new Error("Failed to create user");
}
return response.json();
};
return useMutation({
mutationKey: ["createUser"],
mutationFn: createUserFunction,
});
}