Suspense

The suspense utility exist solely to aid you with any asynchronous rendering.

It takes three arguments and only the first one is required.

suspense(ASYNC_ACTION, LOADING_TEMPLATE, FAILING_FN_RENDER)

  • ASYNC_ACTION: Some async function or one that returns a promise.
  • LOADING_TEMPLATE (optional): Anything you want to render while the action is still pending.
  • FAILING_FN_RENDER (optional): A function that must return something to render when the action fails. This function will get called with the error.

By default, it will render a paragraph saying loading... and if it fails it will render a paragraph with the error message.

html`${suspense(fetchUser, html`<p>user loading...</p>`)}`

This helper can be very powerful with API calls as well as lazy loading parts of the page.

const loadTodos = () => {
  return fetch('/api/todos')
    .then(res => res.json())
    .then(res => html`${repeat(res, renderTodo)}`)
}

html`${suspense(loadTodos)}`

To handle error, you can provide a third argument to handle how to render the error message.

const loadTodos = () => {
  return fetch('/api/todos')
    .then(res => res.json())
    .then(res => html`${repeat(res, renderTodo)}`)
}


html`${suspense(
   loadTodos,
   html`<p>Loading todos...</p>`,
   (error) => html`<error-display message="${error.message}" />`
)}`