Real-time updates in Vue apps with Polling
Tags: vue, javascript, tutorial, typescript
Published: 2023-12-25 09:40:00


When I first discovered a concept of Frontend Polling, I wasn't sure if it is a good idea or not. I was a bit affraid of overloading the server with too many consecutive requests that do not bring value (because we know that the data is not there yet right?)

But the reality is, that when implemented correctly, such polling is not as destructive for the server as it may seem from the first example while they can deliver a lot of value to the users as it allows them to get up to date information without the need to refresh the page.

![Frontend Polling](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/45ghvhdetgd9vp1r8zsb.png)

In this article, I would like to introduce you to the concept of Frontend Polling so that you can try it out in your project and see for yourself if it will be useful in your case 😉

## 🤔 What is Frontend Polling?

There is a really good article about how to achieve it in pure JavaScript that you can check out [here](https://javascript.info/long-polling)

In general, the idea is to have persistent connection with server, that doesn’t use any specific protocol like WebSocket or Server Sent Events.

There are two major ways of achieving polling:

1. `Regular` -> This method triggers polling after certain amount of time, called interval. It will work in several cases (we are using it in Vue Storefront). This is usually achieved by using `setInterval` built in JS function. Let's take a look at following code to see how it works:

```ts
const fetchPosts = async () => {
  try {
    console.log('Fetching new data...');

    const response = await (await fetch(url)).json();

    console.log('Data fetched!')

  } catch(err) {
    console.log('Request failed: ', err.message);
  }
}

setInterval(fetchPosts, 5000);
```

2. `Long` -> Triggering polling after certain response from the endpoint. The best way of explaining how it works is by looking at the following code sample:

```ts
async function subscribe() {
  let response = await fetch("/subscribe");

  if (response.status == 502) {
    // Status 502 is a connection timeout error,
    // may happen when the connection was pending for too long,
    // and the remote server or a proxy closed it
    // let's reconnect
    await subscribe();
  } else if (response.status != 200) {
    // An error - let's show it
    showMessage(response.statusText);
    // Reconnect in one second
    await new Promise(resolve => setTimeout(resolve, 1000));
    await subscribe();
  } else {
    // Get and show the message
    let message = await response.text();
    showMessage(message);
    // Call subscribe() again to get the next message
    await subscribe();
  }
}

subscribe();
```

In general, this polling is really useful to display up to date data to the user without them needing to refresh the page.

If you would like to learn more about Server Side Events or Web Sockets that can bring even more value, check out this [link](https://dev.to/thesanjeevsharma/real-time-updates-polling-sse-and-web-sockets-277i).

## 🟢 How do we use Polling at Vue Storefront?

At Vue Storefront, we utilize the concept of Polling in the VSF Console project which is a storefront hosting and monitoring platform.

{% embed https://youtu.be/du9fwUACFKc %}

You can check out VSF Console documentation [here](https://docs.vuestorefront.io/console) if you are interested.

There is a feature called Performance Auditing that allows to run an audit against a website to get performance insights gathered from Page Speed Insights API and displayed in a visually attractive form:

![VSF Console Polling](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ef1zjlw5p1lh3wfu6akd.gif)

This allows to deliver users up to date performance audit information without them needing to refresh the page which is really good for User Experience.

Apart from just creating this polling locally (if you are staying at the same page) we decided to implement this polling as a global function that utilizes usage of local storage (by using Vue Use that I talked about in my previous article). This allows users to trigger Performance Audit and navigate to another page. When the audit will be successfully finished, user will receive a toast notification that the audit is ready for review. 

What is more, if a user decides to close the website (tab) and reopen it, they will still receive the notification about the audit that was finished because it was saved to check this audit in the local storage. This is another step forward in utilizing polling.

The next step (not necesarily related to polling) would be to implement notification system that requires database, backend endpoints, and whole new desing in the frontend to utilize these notifications as an alternative to toasts. But this is a topic for another article 😃

## 📖 Learn more 

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this [link](https://vueschool.io/courses?friend=baroshem) or by clicking the image below:

[![Vue School Link](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i662jpyni4zs2dlaeud1.png)](https://vueschool.io/courses?friend=baroshem)

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉

## ✅ Summary

Well done! You have just learned about the concept of polling and how you can utilize it in Vue to let user have up to date information in your app. 

Take care and see you next time!

And happy coding as always 🖥️