Replies: 5 comments
-
By JS closure rule, You might need to access mutated cart data directly from swr cache instead. |
Beta Was this translation helpful? Give feedback.
-
That's ok. Because when user adds first product, cart is empty. The issue here is that I want my cart to be updated right after I call |
Beta Was this translation helpful? Give feedback.
-
Ok, if someone is still interested in this - here is working example with react-query. It's basically about optimistic update but without knowing all required params up front. I really don't know how to do it properly in useSWR ( you may take this code and call addProduct and see what is in cart ):
it is working due to the fact that |
Beta Was this translation helpful? Give feedback.
-
You can totally do the same with SWR, set your key as cart and then in your fetcher (which could be unique per key) you can read your cart id from the cookie. Then, in your |
Beta Was this translation helpful? Give feedback.
-
@sergiodxa Do you have a example of the code you are suggesting? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hey, I have hard time figuring out how to deal with usage of SWR and revalidation when key for request is not there from the beginning.
Case looks like that:
I want my guest to add product to cart. But if he doesn't have a cart then I need to create one before adding product to it.
So code looked like this at the beginning:
This code works well if there is a cart id before guest tries to add product.
The issue here is that I don't have cart id when guest tries to add first product.
This code alone is not enough to revalidate, because well, there is no key to which mutate is bound to. I need to add const [isRevalidated, revalidate] = useState(false); and call it after requestToAddProduct. So even though I have most of the data required to show in my UI when requestToAddProduct ends, I can't. I need to manualy refetch whole cart.
So code now actually looks more like that:
I tried to revalidate in createCart method but then, when I call addProduct, useSWR returns data from cache and there is also request race between request that fetches cart and the one that adds product to cart. So I often fetched a cart before product was added and then useSWR returned data from cache.
Also - the issue with this code is that I need to add
isLoading
variable to state. If I want to show loader when user adds product to cart I can't relyaddProduct
solely, because in the case I described I don't get modified cart right afterrequestToAddProduct
andmutate
. I get it after those methods AND refetch.I think solution that solves this problem is bounding mutate not to key but to given useSWR call. Or maybe adding another param like
cacheKey
. But maybe I misunderstand some of the concept here.Beta Was this translation helpful? Give feedback.
All reactions