#Efficiently Managing Payload with Config in Code
17 messages · Page 1 of 1 (latest)
Original message from @cosmic forge - Moved from #general message
Help is on the way! To mark it as solved, use the /solve command. In the meantime, here are some existing threads that may help you:
Documentation:
- The Payload Config - Server vs. Client
- Generating TypeScript Interfaces - Disable declare statement
- Local API - Accessing Payload - Importing it
Community-Help:
Documentation Issue At the page https://payloadcms.com/docs/local-api/overview we see module-level (file-level) initialization. This is not specifically stated, so might be just simplified. Then in...
Okay, I'll take a look, thx!
Had to do it @pale glen 😄
I see that the conclusion is to put const payload = await getPayload({ config }) inside functions.
But the part I fail to understand is that, the onInit() function gets called each time you getPayload().
Unless you have nothing inside that onInit() (yes, can do), or you'll be delayed more if you getPayload() everywhere?
There's not really much overhead after Payload is initialized I think, as the instance gets cached and returned by getPayload
But thatonInit()part is run every time!
It's not
The initialized instance gets cached
And if it exists, then returned with subsequent calls to getPayload
export const getPayload = async (
options: Pick<InitOptions, 'config' | 'importMap'>, // so there is no `disableOnInit` here
): Promise<Payload>
In init():
if (!options.disableOnInit) {
if (typeof options.onInit === 'function') {
await options.onInit(this)
}
if (typeof this.config.onInit === 'function') {
await this.config.onInit(this)
}
}
Since there is no disableOnInit option, onInit(this) is always triggered when init() is called.
if (!cached.promise) {
// no need to await options.config here, as it's already awaited in the BasePayload.init
cached.promise = new BasePayload().init(options)
}
init() is called when there is no cached promise (the first time), so it shouldn't be triggered again later.
But for each page that uses getPayload(), the init() will always be triggered once when you refresh the page. Am I getting this correctly?
So each load of the page will always trigger the onInit(), unless you don't put your getPayload() call there?
Almost
But for each page that uses getPayload(), the init() will always be triggered once when you refresh the page. Am I getting this correctly?
The init function is called only once, then cached. Every subsequent call to getPayload returns the cached instance. This is happening on the server, which does not need to reinitialize itself when a client navigates to a new page. So, it's only called once on initialization and that's it.