Objects stored in pinia are not stable #1146
Unanswered
kawazoe
asked this question in
Help and Questions
Replies: 0 comments
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.
-
Back in the vuex days, I designed a store that could deal with the classic concurrency issue you get when implementing a "search as you type" feature. The problem is that, even with debouncing, it is very common to have multiple search requests in flight at the same time, yet you only care about the result of the last one.
To handle this scenario, I stored a unique key when triggering the API request. I then compare this key to one present in the result of the request and only store its result if they are the same. This works because the store will always contain the key from the last request. If multiple requests are in flight simultaneously, I am guarantied to only keep the result I care about.
Here's a high-level version of what I did (pinia syntax):
I noticed that the then call was creating a closure that meant I didn't even have to bring the key back in my results. I could simply use the closure to keep hold of the request's key for me.
My last intuition was that using
Math.random()
to generate a key might not be ideal. There is a small risk of getting a duplicate value after all, so I switch to a solution that couldn't cause a duplicate: memory references:The idea here is that, it doesn't matter if the store gets serialized for SSR or not. As long as it doesn't happen while a request is ongoing, the keys are guarantied to be unique (they will always be different objects) for each requests as they cannot occupy the same memory location. If the server triggered a request and stored a key, the client will trigger its own request way later which will override the key anyway.
This solution works flawlessly in vuex3, but I noticed an issue when porting it to pinia. The raw value of the stored key (
toRaw(this.key)
) can change in some scenarios. For instance, it seems to work fine on the first call, but doesn't behave correctly on the second. Even thoughthis.key
andkey
have the same content, they aren't the same object. This have been verified with this variant:Output:
In the second call, even though the
_id
is the same ('y' in both cases), the object have been recreated, breaking the equality check. This suggests that object references are not stable in a pinia store.Is this a bug or is it by design?
Is it even a good idea to use objects like this?
How would you accomplish this?
Beta Was this translation helpful? Give feedback.
All reactions