How to use payload in nextjs server actions? #6596
Unanswered
mohamedsobhi777
asked this question in
Q&A
Replies: 1 comment
-
There is an example repo: https://github.com/payloadcms/payload-3.0-demo Based off of the example in that repo, I created this util function: import { getPayloadHMR } from "@payloadcms/next/utilities"
import configPromise from "@/payload/config"
const getPayload = () => getPayloadHMR({ config: configPromise })
export default getPayload Here's an example of using it in a getDocumentById server action that is working for me: "use server"
import "server-only"
import { unstable_cache as cache } from "next/cache"
import getPayload from "@/utils/getPayload"
import type { Options } from "node_modules/payload/dist/collections/operations/local/findByID"
import type { GeneratedTypes } from "payload"
const getDocumentById = <T extends keyof GeneratedTypes["collections"]>({
id,
...findArgs
}: Options<T>): Promise<GeneratedTypes["collections"][T] | undefined> =>
cache(
async () => {
try {
const client = await getPayload()
const document = await client.findByID({ ...findArgs, id, draft: false })
return document
} catch (error) {
console.error("Error fetching document by id", error)
}
},
["getDocumentById"],
{
tags: [typeof id === "string" ? id : id.toString()]
}
)()
export default getDocumentById |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm getting this error when importing payload inside a server action.
const dirname = path.dirname(filename)
13 |
This is the import i'm using (I have also tried getPayloadHMR):
import configPromise from '@/payload.config'
import { getPayload } from 'payload'
Any has successfully managed to access payload inside a server action, or is there an example repo?
Beta Was this translation helpful? Give feedback.
All reactions