Skip to content

Commit

Permalink
Ignore results from other sources in useSource
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Mar 17, 2020
1 parent caedd0f commit 3a597dd
Showing 1 changed file with 27 additions and 11 deletions.
38 changes: 27 additions & 11 deletions packages/react-urql/src/hooks/useSource.ts
Expand Up @@ -18,35 +18,51 @@ import {

import { useClient } from '../context';

let currentSourceId: null | {} = null;

export const useSource = <T>(source: Source<T>, init: T): T =>
useSubscription(
useMemo((): Subscription<T> => {
let hasUpdate = false;
let currentValue: T = init;

// Wrap the source and track its `currentValue`
const updateValue = pipe(
source,
onPush(value => {
currentValue = value;
})
);
const id = {};

return {
// getCurrentValue may be implemented by subscribing to the
// given source and immediately unsubscribing. Only synchronous
// values will therefore reach our `onPush` callback.
getCurrentValue(): T {
if (!hasUpdate) publish(updateValue).unsubscribe();
if (!hasUpdate) {
currentSourceId = id;
pipe(
source,
onPush(value => {
currentValue = value;
}),
publish
).unsubscribe();
currentSourceId = null;
}

return currentValue;
},
// subscribe is just a regular subscription, but it also tracks
// `hasUpdate`. If we're subscribed and receive a new value we
// set `hasUpdate` to avoid `getCurrentValue` trying to subscribe
// again.
subscribe(onValue: () => void): Unsubscribe {
hasUpdate = true;
const { unsubscribe } = pipe(updateValue, subscribe(onValue));
const { unsubscribe } = pipe(
source,
subscribe(value => {
if (currentSourceId === null) {
currentValue = value;
hasUpdate = true;
onValue();
hasUpdate = false;
}
})
);

return () => {
unsubscribe();
hasUpdate = false;
Expand Down

0 comments on commit 3a597dd

Please sign in to comment.