Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for skip to Query and useQuery. #237

Merged
merged 5 commits into from
May 19, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/components/Query.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,23 @@ describe('on error', () => {
expect(childProps).toHaveProperty('error', error);
});
});

describe('skip', () => {
beforeEach(() => {
client.executeQuery.mockReturnValue(fromValue({ data: 1234 }));
});

it('should skip executing the query if skip is true', () => {
mountWrapper({ ...props, skip: true });
expect(client.executeQuery).not.toHaveBeenCalled();
});

it('should not call executeQuery if skip changes to true', () => {
const wrapper = mountWrapper(props);
expect(client.executeQuery).toHaveBeenCalledTimes(1);

// @ts-ignore
wrapper.setProps({ ...props, query: '{ newQuery }', skip: true });
expect(client.executeQuery).toHaveBeenCalledTimes(1);
});
});
35 changes: 22 additions & 13 deletions src/components/Query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ interface QueryHandlerProps {
variables?: object;
client: Client;
requestPolicy?: RequestPolicy;
skip?: boolean;
children: (arg: QueryHandlerState) => ReactNode;
}

Expand All @@ -30,19 +31,27 @@ class QueryHandler extends Component<QueryHandlerProps, QueryHandlerState> {

this.setState({ fetching: true });

const [teardown] = pipe(
this.props.client.executeQuery(this.request, {
requestPolicy: this.props.requestPolicy,
...opts,
}),
subscribe(({ data, error }) => {
this.setState({
fetching: false,
data,
error,
});
})
);
let teardown = noop;

if (!this.props.skip) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moving the check here ensures that both this.unsubscribe will get executed and redefined in preparation for the next query. No more futzing with componentDidUpdate 😅

[teardown] = pipe(
this.props.client.executeQuery(this.request, {
requestPolicy: this.props.requestPolicy,
...opts,
}),
subscribe(({ data, error }) => {
this.setState({
fetching: false,
data,
error,
});
})
);
} else {
this.setState({
fetching: false,
});
}

this.unsubscribe = teardown;
};
Expand Down
42 changes: 33 additions & 9 deletions src/hooks/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,30 +19,36 @@ jest.mock('../client', () => {

import React, { FC } from 'react';
import renderer, { act } from 'react-test-renderer';
// @ts-ignore - data is imported from mock only
import { createClient } from '../client';
import { useQuery } from './useQuery';
import { OperationContext } from '../types';
import { useQuery, UseQueryArgs, UseQueryState } from './useQuery';

// @ts-ignore
const client = createClient() as { executeQuery: jest.Mock };
const props = {
const props: UseQueryArgs<{ myVar: number }> = {
query: '{ example }',
variables: {
myVar: 1234,
},
skip: false,
};
let state: any;
let execute: any;

const QueryUser: FC<typeof props> = ({ query, variables }) => {
const [s, e] = useQuery({ query, variables });
let state: UseQueryState<any> | undefined;
let execute: ((opts?: Partial<OperationContext>) => void) | undefined;

const QueryUser: FC<UseQueryArgs<{ myVar: number }>> = ({
query,
variables,
skip,
}) => {
const [s, e] = useQuery({ query, variables, skip });
state = s;
execute = e;
return <p>{s.data}</p>;
};

beforeAll(() => {
// tslint:disable-next-line
// tslint:disable-next-line no-console
console.log(
'supressing console.error output due to react-test-renderer spam (hooks related)'
);
Expand Down Expand Up @@ -158,7 +164,25 @@ describe('on change', () => {
describe('execute query', () => {
it('triggers query execution', () => {
renderer.create(<QueryUser {...props} />);
act(() => execute());
act(() => execute!());
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-nullary operator for tests, since execute can, from a type perspective, be undefined in the course of running these tests.

expect(client.executeQuery).toBeCalledTimes(2);
});
});

describe('skip', () => {
it('skips executing the query if skip is true', () => {
renderer.create(<QueryUser {...props} skip={true} />);
expect(client.executeQuery).not.toBeCalled();
});

it('skips executing queries if skip updates to true', () => {
const wrapper = renderer.create(<QueryUser {...props} />);

/**
* Call update twice for the change to be detected.
*/
wrapper.update(<QueryUser {...props} skip={true} />);
wrapper.update(<QueryUser {...props} skip={true} />);
expect(client.executeQuery).toBeCalledTimes(1);
});
});
32 changes: 20 additions & 12 deletions src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ export interface UseQueryArgs<V> {
query: string | DocumentNode;
variables?: V;
requestPolicy?: RequestPolicy;
skip?: boolean;
}

interface UseQueryState<T> {
export interface UseQueryState<T> {
fetching: boolean;
data?: T;
error?: CombinedError;
Expand Down Expand Up @@ -39,27 +40,34 @@ export const useQuery = <T = any, V = object>(
const executeQuery = useCallback(
(opts?: Partial<OperationContext>) => {
unsubscribe();

setState(s => ({ ...s, fetching: true }));

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

if (!args.skip) {
[teardown] = pipe(
client.executeQuery(request, {
requestPolicy: args.requestPolicy,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at this now, shouldn't args.requestPolicy also be included in the dependency array for this useCallback? Otherwise we might not recompute it if it changes.

Copy link
Contributor

@andyrichardson andyrichardson May 15, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup I believe so. We're currently allowing users to specify the request policy on a manual query execution but I believe this goes against the way hooks work.

If the request policy changes, that should be reflected in the components state and flow all the way down to the useQuery hook.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed!

...opts,
}),
subscribe(({ data, error }) =>
setState({ fetching: false, data, error })
)
);
} else {
setState(s => ({ ...s, fetching: false }));
}

unsubscribe = teardown;
},
[request.key]
[request.key, args.skip]
);

useEffect(() => {
executeQuery();
return unsubscribe;
}, [request.key]);
}, [request.key, args.skip]);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Last question here for both of you @andyrichardson and @kitten -> should executeQuery be included in the dependency array here? The Hooks FAQ make a big deal about it being unsafe to exclude functions that reference props / state from the dependency array of useEffect calls. So basically this dep array would become just [executeQuery]. I'm also starting to think we might want to useRef unsubscribe. Thoughts?

Copy link
Contributor Author

@parkerziegler parkerziegler May 15, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, didn't get to this 😱 Including it into the array here will probably mean that requestPolicy can change at any time which is generally good 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🆒 that'll come up in the next PR, gonna merge this as is 😄

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@parkerziegler - yeah I think that is necessary 👍


return [state, executeQuery];
};