Tip: Async updates in an Express app

How to use fetch to retrieve data in a Pug template

P1xt
P1xt’s Blog
2 min readFeb 17, 2018

--

Not ready to hop on the React / Angular / Vue bandwagon but still want the view layer of your Express app to have the responsive feel that comes from Async updates to the DOM? Wondering how to build that into a pug template?

This morning I put together a minimal demo that shows how to do just that. It uses vanilla JavaScript to fetch data from the API and update elements of the DOM “on the fly” in response to user events. It’s a very simple demo — you click a button which triggers an event to call a function which fetches some data, then updates elements on the page to reflect the data that was retrieved.

It uses fetch, getElementById and Node.textContent to work it’s magic — all vanilla JavaScript.

The repo is available here for anyone who’d like to browse through the code.

Highlights are:

  • In pug, use script to pull in an external JavaScript.
  • Use a combination of fetch and typical DOM manipulation JavaScript to update the DOM with data retrieved from the API

--

--