Skip to content

Commit

Permalink
Merge new useEffect and useImmediateEffect
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Jun 3, 2019
1 parent 3242444 commit 176fd4b
Showing 1 changed file with 21 additions and 22 deletions.
43 changes: 21 additions & 22 deletions src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { DocumentNode } from 'graphql';
import { useEffect, useCallback, useContext, useRef, useState } from 'react';
import { useCallback, useContext, useRef, useState } from 'react';
import { pipe, subscribe } from 'wonka';
import { Context } from '../context';
import { OperationContext, RequestPolicy } from '../types';
Expand Down Expand Up @@ -42,35 +42,30 @@ export const useQuery = <T = any, V = object>(
data: undefined,
});

useEffect(() => {
return () => {
isMounted.current = false;
}
}, []);

const executeQuery = useCallback(
(opts?: Partial<OperationContext>) => {
unsubscribe.current();

if (args.pause) {
setState(s => ({ ...s, fetching: false }));
unsubscribe.current = noop;
} else {
setState(s => ({ ...s, fetching: true }));
return;
}

const [teardown] = pipe(
client.executeQuery(request, {
requestPolicy: args.requestPolicy,
...opts,
}),
subscribe(
({ data, error }) =>
isMounted.current && setState({ fetching: false, data, error })
)
);
setState(s => ({ ...s, fetching: true }));

unsubscribe.current = teardown;
}
const [teardown] = pipe(
client.executeQuery(request, {
requestPolicy: args.requestPolicy,
...opts,
}),
subscribe(
({ data, error }) =>
isMounted.current && setState({ fetching: false, data, error })
)
);

unsubscribe.current = teardown;
},
[request, client, args.pause, args.requestPolicy]
);
Expand All @@ -79,7 +74,11 @@ export const useQuery = <T = any, V = object>(
// treats it as a normal effect
useImmediateEffect(() => {
executeQuery();
return () => unsubscribe.current();

return () => {
isMounted.current = false;
unsubscribe.current();
};
}, [executeQuery]);

return [state, executeQuery];
Expand Down

0 comments on commit 176fd4b

Please sign in to comment.