What happens if key is an empty string when calling useSWR? #1810
Replies: 3 comments 1 reply
-
I have figured out a bit of a hacky workaround for this: const { data } = useSWR(['', 'foo'], fetcher) The The cache key is made up of all the items in the supplied array. So if you want your empty string to be used as a cache key, simply supply a non-falsy dummy string for all requests as the second array item. Just make sure you use the same string for all requests. It will be passed to Perhaps there's a better solution than this, but I'll take it for now. |
Beta Was this translation helpful? Give feedback.
-
If the key is falsy SWR won’t do anything (it’s treated as “paused”). But I’m curious to know what’s the use case for an empty key — it’s usually the identifier for the resource. |
Beta Was this translation helpful? Give feedback.
-
Ah. Great question. (And here's where you'll likely tell me "you're doing it all wrong"). Use case is a customisable autocomplete dropdown with typeahead. The results displayed are fetched from multiple resources, the number of which can be specified by the parent component. Therefore I have built a fetcher that fires off N parallel API requests and combines the results into a single array with This works perfectly. Having an empty array cached against an empty string is great as I have |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
If I provide an empty string as the
key
argument, for example:am I correct in thinking that this essentially does nothing? i.e. the fetcher is not called, nothing is cached,
data
remains unchanged? Maybe I'm missing something in the docs but I can't find anything that addresses this.Beta Was this translation helpful? Give feedback.
All reactions