Automatically update dashboard on an interval?

Hi I’m new to observable and really enjoy it so far. I’ve made a dashboard which queries an api and displays data. I’d like to put it up on a monitor on the wall at work, but to do that it needs to automatically update with the latest data.

What is the idiomatic way to query the api for fresh data on an interval?

I could bake setInterval into the flow somewhere to handle the refresh “inside the cell” but I’m curious if there’s some easier way to do what is effectively re-running the cell (shift+enter behavior).

1 Like

My instinct would be to wrap the code in Promises.tick in a while (true) loop, see e.g.:

1 Like

Hi there, @apellerano-pw

I’m sure that others will chime in as well — but I personally enjoy using asynchronous generators for this purpose.

And don’t let the fancy name scare you. What we’re really talking about here is a simple while loop that runs forever, waiting for a certain amount of time before proceeding to loop again.

{
  while (true) {
    yield (await fetch("https://your-api-goes-here")).json();
    await Promises.delay(milliseconds);
  }
}

For a live example, let’s fetch the current time in Kiritimati from a remote API server, every N seconds:

3 Likes

Also see:

1 Like

That worked like a charm, thanks all! Here’s a rough sketch of the periodically function I wrote to power my existing api fetch functions

periodically = async function* (fn, interval, ...rest) {
  while (true) {
    yield fn(...rest);
    await Promises.delay(interval);
  }
}

usage:

periodically(queryTheApi, 5000, someArg, someOtherArg)
2 Likes