hyperstatic icon indicating copy to clipboard operation
hyperstatic copied to clipboard

Also run Init in production

Open mdings opened this issue 4 years ago • 2 comments

Is it correct that the exported Init function for pages only runs in develop mode? In production it seems that the data is being loaded from the cached json-file.

Although a nice feature, I'm running into cases where I need the latest data from the server to be fetched and hydrate any content from cache. For example: I have a website where pages can be created inside a CMS. When building the website all the pages are pre-rendered and cached, which is amazing. However, whenever I make a small change inside the content for the page I would need to rerender the full website in order for that change to be visible. With the previous version the Init function would also still run in production mode. So the browser renders the static version from the server. Then the Init-function fetches the latest version from the server and goes ahead and updates the content that was changed. So I get the lastest version no matter what.

Is that still possible with the current version of hyperstatic?

mdings avatar Jun 05 '21 21:06 mdings

Hello @mdings !

I think you could achieve what you're looking for by creating a hyperapp http effect similar to the loadStatic one in the init of your pages, example:

// in some utils file...
const promiseLoaderFx = async (dispatch, { loader, action, error }) {
  try {
    const data =  await loader();
    dispatch([action, data])
  } catch (e) {
    dispatch([error, e])
  }
}

const promiseLoader = (args) => [promiseLoaderFx, args]

// In you page file..
export const init = (state, location) => [
  state,
  loadStatic({
    loader: async () => {
      const data = await getPageData(`https://foobar.com/api/${location.params.id}`)
      return data
    },
    action: HandleData,
    error: HandleError
  }),
  promiseLoader({
    loader: async () => {
      const data = await getPageData(`https://foobar.com/api/${location.params.id}`)
      return data
    },
    action: HandleData,
    error: HandleError
  }),
]

This will load the data as usual via the hyperstatic json cache, but then also via your live API at runtime (in production)

loteoo avatar Jun 06 '21 05:06 loteoo

Hmm that sounds like a good idea. But that doesn't trigger the promiseLoader effect on navigation. So I guess I have to add the same function to the pageChange callback as well. Is that correct?

mdings avatar Jun 06 '21 14:06 mdings