refetch a specific query on error e.g. on network error and reconnect #436
-
Hi, I'm using Apollo Client on a chat app and subscriptions to get the latest message from server. On mobile devices internet might not be stable thus the user might "miss" some messages due to disconnected sockets. Is there a way to refetch a specific query on network reconnect? One example on older ws client with Apollo would be: if (this.messagesSubscription) {
this.messagesSubscription();
} // clear the event subscription
if (this.reconnected) {
this.reconnected();
}
} else if (!this.reconnected) {
this.reconnected = wsClient.onReconnected(() => {
this.props.refetch(); // check for any data lost during disconnect
}, this);
} thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Of course! By leveraging the client events, you can detect a reconnect and act accordingly. Here's an adapted client: import { createClient, Client, ClientOptions } from 'graphql-ws';
import { refetchSomeQueries } from './on-reconnected';
interface ClientWithOnReconnected extends Client {
onReconnected(cb: () => void): () => void;
}
function createClientWithOnReconnected(
options: ClientOptions,
): ClientWithOnReconnected {
let abruptlyClosed = false;
const reconnectedCbs: (() => void)[] = [];
const client = createClient({
...options,
on: {
...options.on,
closed: (event) => {
options.on?.closed?.(event);
// non-1000 close codes are abrupt closes
if ((event as CloseEvent).code !== 1000) {
abruptlyClosed = true;
}
},
connected: (...args) => {
options.on?.connected?.(...args);
// if the client abruptly closed, this is then a reconnect
if (abruptlyClosed) {
abruptlyClosed = false;
reconnectedCbs.forEach((cb) => cb());
}
},
},
});
return {
...client,
onReconnected: (cb) => {
reconnectedCbs.push(cb);
return () => {
reconnectedCbs.splice(reconnectedCbs.indexOf(cb), 1);
};
},
};
}
const client = createClientWithOnReconnected({
url: 'ws://ireconnect:4000/and/notify',
});
const unlisten = client.onReconnected(() => {
refetchSomeQueries();
}); |
Beta Was this translation helpful? Give feedback.
-
Amazing, thank you @enisdenjo, the code sample helped a lot! Glad you added it as a recipe too! |
Beta Was this translation helpful? Give feedback.
Of course! By leveraging the client events, you can detect a reconnect and act accordingly. Here's an adapted client: