#useFetch caching layer

5 messages · Page 1 of 1 (latest)

paper garden
#

Imagine you want to fetch the same data from two (three, five, ten?) different components.

// compA
const { data: users } = useFetch('/some/users', { key: 'users' });

// compB
const { data: users } = useFetch('/some/users', { key: 'users' });

You will see two network requests that run in parallel, but resolved sequentially. One by one as a waterfall.
Both, compA and compB will be updated (re-rendered) at once after all requests are resolved.
That means if you have 10 components, you will wait x10 times longer to see the visual response on the page.

What heppening behind the scenes (from my understanding).

  • got request 1, fetching
  • got request 2. Oh, we have the same request (1) already. I will wait it to be resolved, but will not use it. Only then (2) will be executed.
  • got request 3. Oh, we have the same requests (1, 2) already. I will wait them all to be resolved, but will not use their data. Only then (3) will be executed.
  • and so on. The more requests, the longed the waiting chain.

Is there a way to change it to

  • got request 1, fetching
  • got request 2. Oh, we have the same request (1) already. I will wait it to be resolved, and you all share it's data
  • got request 3. Oh, we have the same request (1) already. I will wait it to be resolved, and you all share it's data
  • and so on. No waiting chain. As soon as (1) resolved, all other also resolved. Singleton-like pattern.

Any answer would be appreciated!

clear sorrel
#

I think having useFetch in 10 different components will lead to performance issues on SSR page load.

On server side, useFetch eventually uses serverPrefetch hook from Vue. which will pause the Vue server renderer until the serverPrefetch hook for a component is complete. So if you have 10 different components doing 10 different useFetch, that will be 10 sequential network requests on server side

paper garden
#

I think it should be fine if you re-route all further requests to the first promise.
I'll get back to you here in a few days with the update. Thanks once again for the feedback!

paper garden
static stone
#

Hello @paper garden I'm looking for similar case. At Nextjs there is great SWR package, at Vue side there is SWRV tho it doesn't have all of the React version features ;/