Is using Cache as global state a good idea? and is this the best way to do it? #985
-
Hi guys, So I have a stock app where I need to load the user positions for each symbol. So I fetch it with SWR. Thing is, I want to only validate if the cache doesn't have the data of that symbol. If the user goes to another page of another symbol, we should fetch his positions for that symbol and store it in cache under a different key. I got the implentation to work and it's all good. I'm really curious if it's a good idea and if my way is the best way to do it. I wish we had access to the key in the const { data: userPositionsPerSymbol, error: fetchError } = useSWR(
symbol ? [`/positions`, 'symbol', symbol] : null,
axiosFetcherWithParams,
{
revalidateOnMount: !cache.has(`/positions?symbol=${symbol}`), // here we refer to the SWR cache
revalidateOnFocus: false,
revalidateOnReconnect: false,
},
); The fetcher is here: export const axiosFetcherWithParams = (
url: string,
queryKey: string,
queryVal?: string,
): any =>
Axios.get(`${url}?${stringify({ [queryKey]: queryVal })}`).then((res) => res.data); I tried to pass the object directly What do you guys think? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Also I am not sure if this a bad idea or something, but I had this working before and had to change it to adhere to the usage mentioned in the docs for arguments. But I wanna ask is this wrong?: const { data: userPositionsPerSymbol, error: fetchError } = useSWR(
symbol ? `/positions?symbol=${symbol}` : null,
axiosFetcher,
{
revalidateOnMount: !cache.has(`/positions?symbol=${symbol}`), // here we refer to the SWR cache
revalidateOnFocus: false,
revalidateOnReconnect: false,
},
); It greatly simplifies my fetcher... |
Beta Was this translation helpful? Give feedback.
-
Anyone? 😅 |
Beta Was this translation helpful? Give feedback.
-
In general, I think, the cache should be considered an implementation detail. You can access it directly, but you're missing out on some of useSWR's abstractions, which can make things more complicated. In this particular case, I don't see a way in the useSWR API to do what you're wanting, so accessing the cache seems fine. (If it helps, you're not using cache as arbitrary global state; you're just using it for more fine-grained read-only knowledge of useSWR's own behavior.) |
Beta Was this translation helpful? Give feedback.
In general, I think, the cache should be considered an implementation detail. You can access it directly, but you're missing out on some of useSWR's abstractions, which can make things more complicated.
In this particular case, I don't see a way in the useSWR API to do what you're wanting, so accessing the cache seems fine. (If it helps, you're not using cache as arbitrary global state; you're just using it for more fine-grained read-only knowledge of useSWR's own behavior.)