Like what we’re doing? Star us on GitHub!

Why are the parameters for collection hooks typed as being possibly undefined?

last year
1 1

As you've probably seen, I've done a bad thing and enabled strict mode in my tsconfig.json

It's saying that args passed into hooks can be undefined so I have to wrap my mutations in an if block. My concern is that if I'm not returning data from say a beforeChange hook, would that result in wiping out some data?

export const uploadHook: CollectionBeforeChangeHook = async (args) => {
  if (args) {
    const { req, data } = args
    if (req?.files?.file) {
      let uploadedFile: UploadedFile
      if (Array.isArray(req.files.file)) {
        uploadedFile = req.files.file[0]
      } else {
        uploadedFile = req.files.file

      const adapter = getAdapter()
      await adapter.upload(data.filename, uploadedFile)

    return data

Is there any situation where a hooks args should be undefined? What happens to the resulting data if I return undefined from a hook?

  • jmikrut
    Payload Team
    last year

    A lot of good questions in here. First up, I have no idea why args was set to being optional. We just deployed 0.9.3, which makes args required. That will simplify some of your logic.

    Also, you don't need to return data from collection hooks, global hooks, or field hooks. If you don't return data, Payload will fall back on the default incoming data.

    Does this answer your questions?

    1 reply
  • richardvanbergen
    last year

    Yes it does! I was just being paranoid because I didn't want to accidentally delete peoples media with the cloud storage plugin. 😅

Open the post
Continue the discussion in GitHub
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More