Skip to content

Commit

Permalink
Simplify pause argument in useQuery (#278)
Browse files Browse the repository at this point in the history
  • Loading branch information
andyrichardson authored and kitten committed Jun 8, 2019
1 parent edc18db commit 36c5d59
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 20 deletions.
9 changes: 3 additions & 6 deletions src/hooks/useImmediateEffect.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
/* eslint-disable react-hooks/exhaustive-deps */

import { useRef, useEffect } from 'react';
import { noop } from '../utils';
import { useRef, useEffect, EffectCallback } from 'react';

enum LifecycleState {
WillMount = 0,
DidMount = 1,
Update = 2,
}

type Effect = () => () => void;

/** This is a drop-in replacement for useEffect that will execute the first effect that happens during initial mount synchronously */
export const useImmediateEffect = (
effect: Effect,
effect: EffectCallback,
changes: ReadonlyArray<any>
) => {
const teardown = useRef(noop);
const teardown = useRef<ReturnType<EffectCallback>>(undefined);
const state = useRef(LifecycleState.WillMount);

// On initial render we just execute the effect
Expand Down
22 changes: 8 additions & 14 deletions src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,7 @@ export const useQuery = <T = any, V = object>(
(opts?: Partial<OperationContext>) => {
unsubscribe.current();

// If useQuery is currently paused, set fetching to
// false and abort; otherwise start the query
if (args.pause) {
setState(s => ({ ...s, fetching: false }));
unsubscribe.current = noop;
return;
} else {
setState(s => ({ ...s, fetching: true }));
}
setState(s => ({ ...s, fetching: true }));

[unsubscribe.current] = pipe(
client.executeQuery(request, {
Expand All @@ -68,16 +60,18 @@ export const useQuery = <T = any, V = object>(
})
);
},
[args.pause, args.requestPolicy, client, request, setState]
[args.requestPolicy, client, request, setState]
);

// This calls executeQuery immediately during the initial mount and
// otherwise behaves like a normal useEffect; We call executeQuery
// everytime it, i.e. its input like request, changes
useImmediateEffect(() => {
if (args.pause) {
unsubscribe.current();
return setState(s => ({ ...s, fetching: false }));
}

executeQuery();
return () => unsubscribe.current();
}, [executeQuery]);
}, [executeQuery, args.pause, setState]);

return [state, executeQuery];
};

0 comments on commit 36c5d59

Please sign in to comment.