Skip to content

usePolling

Composable for polling with fetch state. Combines useAsyncState with useIntervalFn for non-query polling scenarios (e.g. when you don't need useQuery caching).

Basic Usage

vue
<script setup>
import { usePolling } from "@baklavue/composables";

const { data, isLoading, pause, resume } = usePolling(
  () => fetch("/api/status").then((r) => r.json()),
  { interval: 5000 }
);
</script>

<template>
  <div>
    <div v-if="data">Status: {{ data.status }}</div>
    <button @click="pause">Pause</button>
    <button @click="resume">Resume</button>
  </div>
</template>

Pause in Background

By default, polling pauses when the tab is hidden:

vue
<script setup>
import { usePolling } from "@baklavue/composables";

const { data } = usePolling(
  () => fetch("/api/live").then((r) => r.json()),
  { interval: 3000, pauseInBackground: true }
);
</script>

API

usePolling

typescript
usePolling<T>(fetchFn: () => Promise<T>, options): UsePollingReturn<T>

Options

PropertyTypeDefaultDescription
intervalnumberrequiredPolling interval in ms
immediatebooleantrueRun first fetch immediately
initialDataT-Initial data before first fetch
pauseInBackgroundbooleantruePause when tab is hidden
onSuccess(data: T) => void-Callback on success
onError(error: Error) => void-Callback on error

Return Value

PropertyTypeDescription
dataRef<T | undefined>Fetched data
errorRef<Error | null>Error if fetch failed
isLoadingRef<boolean>True while fetch is in flight
pause() => voidPause polling
resume() => voidResume polling
isActiveRef<boolean>True when polling is active

usePolling vs useQuery refetchInterval

usePollinguseQuery refetchInterval
CachingNoYes
Use caseSimple polling, non-cached dataCached API data that needs periodic refresh