Designing a composable in Vue.js to continuously poll data after the "x" interval.
What is Polling?
It is defined as the process when a client requests a particular piece of data at regular intervals (maybe every x seconds) and the server reverts with a usual response with the required data.
Composable
Let's write a composable usePolling
inside src/composables/usePolling.ts
import { ref, onMounted, onUnmounted } from "vue";
const usePolling = (method, timeInterval = 10000) => {
const interval = ref(null);
const callMethod = ref(method);
const isPolling = ref(false);
const clear = () => {
clearInterval(interval.value);
interval.value = null;
isPolling.value = false;
};
const fetchData = (poll = true) => {
callMethod.value();
if (poll) {
// start interval
interval.value = setInterval(() => {
callMethod.value();
}, timeInterval);
} else {
clear();
}
};
const start = () => {
// clear any existing polling calls
clear();
// set polling flag to true
isPolling.value = true;
// fetch data
fetchData();
};
onMounted(() => isPolling.value && fetchData());
onUnmounted(clear);
return {
start,
clear,
};
};
export default usePolling;
Component:
Now, let's use this composable inside any component.
<script setup>
import { onMounted } from "vue";
import usePolling from "../composables/usePolling";
const apiCall = async () => {
console.log("api call");
// const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
// const data = await response.json();
// console.log(data);
};
const { start, clear } = usePolling(apiCall, 1000);
onMounted(start);
</script>
<template>
<h1>Hello world!</h1>
</template>
Top comments (0)