carvajalconsultants / apollo-link-offline

An Apollo Link to queue mutations when offline or network errors exist.
MIT License
71 stars 15 forks source link

Left behind optimistic responses in apollo cache #6

Closed ChrisLincoln closed 4 years ago

ChrisLincoln commented 4 years ago

Our entity create scheme is to have our backend assign an item's ID and we return it in the mutation query response:

mutation createFoo(fooInput) {
  id  <-- type on the server is INT, but is a nice string type on front end
  name
}

For my optimistic response, I am assigning a uuid to the ID.
1) Following a successful re-connection, the library correctly re-fires the mutation, but I am left with a dangling cache item from the previously failed transaction. Unless I'm just doing something wrong, with the setup, I think a callback from the sync function would come in handy.

2) I would like to have UI to indicate how many Q'd items are pending. I know I can poll OfflineLink.queue, but it would be good if we could subscribe to changes in a react-ish sort of way.

ChrisLincoln commented 4 years ago

Re: 2) I just noticed syncStatusQuery in the code. That should take care of that!

miguelocarvajal commented 4 years ago

Hey Chris!

Glad you found the syncStatusQuery solution, that's exactly what it's there for.

Regarding point #1, this is actually more of an Apollo Cache question. I've never done this where the server "changes" the primary key. I'm assuming you'll have to write a custom function that will determine that the UUID version of the record is the same one as the one with the INT primary key (no out-of-the-box logic will do this).

Not sure how to help you. Have you tried searching the Apollo issues?

ChrisLincoln commented 4 years ago

I've been following all forms of blogs and tutorials to get the offline feature going. I've got lots of new players in my link chain--that I probably don't need with your solution. By setting breakpoints in the mutation update callback, I can see that apollo puts the optimistic response in the cache and then removes/replaces it with the real response on a live, online transaction. I'm not real link savvy, but I don't see how any bookkeeping is possible on their part with this mechanism. In this case, I am not impacted as I don't any UI (at the moment) that depends on these mutation results.

miguelocarvajal commented 4 years ago

Yup yup... it definitely is Apollo that is doing this.

If you don't mind the stale record being kept in your cache (which should be garbage collected at some point if you're using Apollo 3.0) then you should be ok.

I think the best way to do what you're looking to do is keep the same ID and have another field to determine if the record has been persisted by the backend (which is what we do). For example you can have a timestamp field that only the backend sets when the record has been successfully persisted, or maybe even a version field (as with optimistic locking).

Hope this helps!