#Efficiently Managing Payload with Config in Code

17 messages · Page 1 of 1 (latest)

whole relicBOT
#

const payload = await getPayload({ config })
About this, should I export one payload from a file so I don't have to load the config every time, which runs the onInit()?
Or should I just include this line per page (or file) that need it?

stone stumpBOT
#

Original message from @cosmic forge - Moved from #general message

#
steady coral
cosmic forge
#

Okay, I'll take a look, thx!

steady coral
#

Had to do it @pale glen 😄

cosmic forge
#

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 that onInit() part is run every time!

pale glen
#

It's not

#

The initialized instance gets cached

#

And if it exists, then returned with subsequent calls to getPayload

cosmic forge
#
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?

pale glen
# cosmic forge ```ts export const getPayload = async ( options: Pick<InitOptions, 'config' | ...

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.

cosmic forge
#

I think I know why now... In dev mode, it always reload that payload instance!

#

Not in production, lol...