Merry Christmas to you all!
Here is a problem I currently have:
I'm trying to use Payload to sort of "cache" data from an external API and refetch it after a certain amount of time.
Setup:
const MyGlobal: GlobalConfig = {
slug: 'my-global',
fields: [
{
name: 'apiRequestKey',
type: 'text',
hooks: {
beforeChange: [populateData],
afterRead: [populateData],
},
}
{
name: 'updatedAt',
type: 'date',
admin: {
hidden: true,
},
},
{
name: 'apiData',
type: 'number',
admin: {
hidden: true,
},
},
]
}
Inside the hook, I check if updatedAt is expired, and refetch the apiData from an external API. Now if I try to use the local API with payload.updateGlobal()
to write the new data and current timestamp in the database, the update function will trigger the afterRead hook again, before the data is changed, causing an infinite loop.
Possible solutions would be:
Does anybody have an idea for an elegant solution to this problem? Any help is appreciated.
I solved it for now using an early return with
req.payloadAPI === 'local' && operation === 'read'
However, I would still be interested in suggestions for other solutions, since the potential for an endless loop is still present, if the data changes in a specific way. I would still prefer to be able to disable hooks on the update call.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.