Repository navigation
Better way for conditional data fetching. #2618
Unanswered
yash-sharma01
asked this question in
Ideas
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 |
1 reply
|
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) ] }); |
3 replies
|
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...) |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
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.
All reactions