I sometimes get a race condition when trying to use onSubscription hook from @apollo/react-hooks package in the following way.
let { data, loading, error } = useSubscription(MY_SUBSCRIPTION)
if (loading) return 'Loading...';
if (error) return 'Error...';
...
When I load the page, most of the time data gets filled perfectly and eventually loading will turn false, but every ~5th try there's some kind of race condition where loading stays true forever and data is undefined.
GraphQL query:
export const EXERCISE_SUBSCRIPTION = gql`
subscription {
exercises {
id
title
tasks {
id
title
start_time
end_time
}
}
}
`;
Package version is the (currently) latest:
@apollo/react-hooks": "^3.1.0-beta.0", but I have also tried with previous versions.
Has anyone experienced something similar and know how to solve it?
If you run into this issue, I found a workaround hack. You can see that when I add the callback option onSubscriptionData, the data IS present in there, but somehow does not end up in the data object outside.
// <HACK>
// sometimes data object is empty, but onSubscriptionData is filled.
// in that case use data from onSubscriptionData method.
const [dataFromCb, setDataFromCb ] = useState(null)
let { data, loading } = useSubscription(INJECT_SUBSCRIPTION, {
onSubscriptionData: (res) => {
setDataFromCb(res.subscriptionData.data)
},
});
if (loading && !dataFromCb) return 'Loading...';
data = (data === undefined) ? dataFromCb : data;
// </HACK>