![](/img/trans.png)
[英]How to fetch data from Firebase in getServerSideProps with NextJs
[英]how to correctly fetch data in getServerSideProps
使用 Next.js 我遇到了这个问题:
一到达pages/users ,我就收到了这个错误
./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0
Module not found: Can't resolve 'dns'
Import trace for requested module:
./node_modules/mongodb/lib/index.js
./models/user/addedUserModel.js
./pages/api/users/index.js
./pages/users.js
https://nextjs.org/docs/messages/module-not-found
我正在尝试从getServerSideProps获取所有用户,内部页面/用户
import { Layout, Meta, Card, Button } from "../components/ui";
import {useAxios} from "../utils/hooks/requests/useAxios";
import {useNotifications} from "../context/notifications/notifications_context";
const Users = ({users}) => {
const {handleDeleteRequest} = useAxios("api/users");
const {notification} = useNotifications()
const removeUser = async (_id) => {
await handleDeleteRequest(_id)
}
return (
<>
<Layout>
<Meta title="Users"/>
<Card>
{users.addedUsers.map(user => <div className="flex border-b items-center justify-between"
key={user._id}>
<div className="p-2">
<h2>{user.name}</h2>
</div>
<div>
<Button onClick={() => removeUser(user._id)} className="bg-red-500">Delete</Button>
</div>
</div>)}
</Card>
</Layout>
{notification.text ? <div
className={`${notification.isError ? 'bg-red-500 ' : 'bg-green-500 '} absolute top-0 left-0 w-full p-2 flex items-center justify-center text-white font-semibold`}>
<p>{notification.text}</p>
</div> : null}
</>
)
}
export default Users;
export async function getServerSideProps() {
const res = await fetch("http://localhost:3000/api/users")
const users = await res.json()
return {
props: { users }
}
}
api端点的文件夹结构如下-> api/users/index.js
在pages/users文件夹下,我有一个[id].js文件来删除单个用户。
所以问题出在 getServerSideProps function 或者我还缺少其他东西来摆脱这个dns
错误?
另外,我想在删除其中一个用户后重新获取所有用户,以便在不刷新页面的情况下获得新的用户列表。 getServerSideProps对完成这项工作没有用吗?
getServerSideProps
允许您在呈现页面之前在服务器端获取数据。 这意味着当用户访问pages/users
页面时,数据将从服务器获取并作为 props object 的一部分返回给组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.