Better way for conditional data fetching. #2618
Replies: 3 comments 4 replies
-
Thanks! It makes sense, my current concern is that do we need two ways to do the same thing (not sure about deprecating this existing approach). Maybe we need a transition period. Perhaps in your internal codebase you can create a util hook on top of SWR to add a |
Beta Was this translation helpful? Give feedback.
-
I use a middleware for that: /**
* Middleware to conditionally skip swr hook execution.
*/
export const swrSkip = (skip: unknown = true): Middleware => {
return (useSWRNext) => {
return (key, fetcher, config) => {
return useSWRNext(skip ? null : key, fetcher, config);
};
};
}; Usage: useSWR(path, fetcher, { use: [ swrSkip(true) ] }); |
Beta Was this translation helpful? Give feedback.
-
I believe that this new prop is very beneficial for the lib, because leaving the Null Key we lose access to the current cache data. With a separate configuration, the hook will be able to return the cache data and still know whether or not to call the fetcher (Whether when requested manually or even in automatic situations such as revalidateOn...) |
Beta Was this translation helpful? Give feedback.
-
Currently, useSWR allows conditional data fetching by passing null as a key parameter.
This approach works fine in almost all cases. However, there are other packages that handle conditional data fetching in a completely different manner. For example, RTK Query from Redux Toolkit has a boolean parameter in the options object called "skip" that can be used to skip the request for certain conditional logic.
The RTK Query approach looks much cleaner and maintainable when we have a long key/URL and multiple conditions to check.
It would be great if useSWR could have something like this for conditional data fetching.
Beta Was this translation helpful? Give feedback.
All reactions