inertia icon indicating copy to clipboard operation
inertia copied to clipboard

Add poll feature

Open HassanZahirnia opened this issue 3 years ago • 0 comments

This PR is for adding a poll feature to Inertia ( similar to Livewire's wire:poll directive ) which allows users to periodically pull data from the backend (via Inertia.reload() function). This provides a nice option for users who want to keep some of their data fresh without resolving to things like websockets and other advanced techniques.

import { usePoll } from '@inertiajs/inertia-vue3'

usePoll() 
// Calls Inertia.reload() every 2 seconds.

usePoll(5000)
 // Same as above but every 5000ms.

usePoll(['stats'])
 // Only reloads the `stats` prop, which is done by passing the array to `only` option of `Inertia.reload`

usePoll(['contacts'], 10000)
// Reloads the `contacts` prop every 10 seconds

usePoll({
   interval: 3000, // default: 2000
   keepAlive: true, // default: false
   startImmediately: false, // default: true
   startWhen: () => !! Checkbox.value, // default: undefined
   stopWhen: isPageScrolled, // default: undefined
   reloadOptions: { // default : undefined
      only: ['organizations'],
      preserveScroll: false,
      // Insert any other valid Inertia.reload options ...
   }
})
// You could also pass an object to manually set all options available.

const { startPoll, stopPoll } = usePoll()
// You can also deconstruct the start and stop functions to have more control over the interval.

The story behind this idea : Before I got into Inertia, as I was reading articles about the differences between Livewire and Inertia, I came across Livewire's wire:poll directive which really made me go "wow!" At the time I thought this was the most impressive feature of this framework. I'm sure there are lots of other people in the community who might feel the same and could use this feature to facilitate the process to have a "semi-realtime" data for their users. So I thought why not make this available for Inertia users ?

Credits: Thanks to @innocenzi for helping with some of the stuff 😊

HassanZahirnia avatar Jan 21 '22 11:01 HassanZahirnia