Kong / swrv

Stale-while-revalidate data fetching for Vue

Home Page:https://docs-swrv.netlify.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Stop revalidation on router change

vortechron opened this issue · comments

When I enabled refreshInterval=7000, every time i navigated to another page, the refetching still keep going, when i navigate to many page, my calls are build up in the background... so my current fix is to use onBeforeRouteLeave and un-render swrv component, is there any way that i can change config dynamically so that i can set refreshInterval = 0 when user navigate to other page?

There's a lot of detail missing here in order to help understand what is actually happening in your app. Can you provide a minimal reproduction?

@adamdehaven Ive made simple example of how messy this will become.. I'm not sure if I'm doing it wrong.. if u have better suggestion please let me know

https://github.com/vortechron/ionic-swr-example

Screenshot 2022-09-16 at 6 18 25 PM

I'm not super-familiar with the Ionic Framework you are using; however, according to their docs:

ionViewWillLeave - Can be used for cleanup, like unsubscribing from data sources. Since beforeUnmount might not fire when you navigate from the current page, put your cleanup code here if you do not want it active while the screen is not in view.

It appears that beforeUnmount (or onUnmounted if using the Composition API) may not fire, meaning swrv's cleanup code will never get called. You'll have to handle this yourself by utilizing Ionic's provided hook as described above.

Using your code as an example

import { onIonViewWillLeave } from '@ionic/vue'

onIonViewWillLeave(() => {
  // your code here
})

@adamdehaven i still don't have any idea on how to stop/clear the timer because it's already initiated, unless config can be dynamically set or turn to ref or something.. what u suggest i should put on that hook onIonViewWillLeave hook?

Just an example, but you could use dependent fetching to only fetch if the page is active.

So something like this (again, just pseudo-code here, usage may vary), using your Tab2Page.vue as an example. Only including the relevant imports and code:

import { onIonViewWillLeave, onIonViewDidEnter } from '@ionic/vue'
import { watch, ref } from 'vue'

const viewIsActive = ref(true)

const { data, error } = useSWRV(
  'https://jsonplaceholder.typicode.com/todos/1?tab2=1',
  (url) => viewIsActive.value && fetch(url).then((r) => r.json()),
  { refreshInterval: 3000 }
)

onIonViewDidEnter(() => {
  viewIsActive.value = true
})

onIonViewWillLeave(() => {
  // Since this is set to `false` when the view is unmounted, the fetcher will not continue to fire
  viewIsActive.value = false
})

@adamdehaven damn, i didnt realize that functionality exists, thanks man, this solves my issues.