Skip to content

Commit

Permalink
Fix useVolatileQuery request (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
k-ode authored Sep 27, 2023
1 parent a2e651d commit e282801
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 30 deletions.
4 changes: 4 additions & 0 deletions packages/mst-query/src/MstQueryHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,10 @@ export class MstQueryHandler {

run(options: QueryOptions = {}) {
const endpoint = this.options.endpoint ?? this.queryClient.config.queryOptions?.endpoint;

if (!endpoint) {
throw new Error('No query endpoint or global endpoint configured');
}

this.setVariables({ request: options.request, pagination: options.pagination });
this.options.meta = options.meta;
Expand Down
29 changes: 4 additions & 25 deletions packages/mst-query/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,31 +147,10 @@ export function useVolatileQuery(
) {
const queryClient = useContext(Context)! as QueryClient<any>;
const query = useRefQuery(VolatileQuery, queryClient);
const [observer] = useState(() => new QueryObserver(query, true));

options = mergeWithDefaultOptions('queryOptions', options, queryClient);

useEffect(() => {
if (options.endpoint) {
query.__MstQueryHandler.options.endpoint = options.endpoint;
}

observer.setOptions(options);

return () => {
observer.unsubscribe();
};
}, [options]);
if (!query.__MstQueryHandler.options.endpoint) {
query.__MstQueryHandler.options.endpoint = options.endpoint as any;
}

return {
data: query.data as typeof query['data'],
error: query.error,
isFetched: query.isFetched,
isLoading: query.isLoading,
isRefetching: query.isRefetching,
isFetchingMore: query.isFetchingMore,
query: query,
refetch: query.refetch,
cachedAt: query.__MstQueryHandler.cachedAt,
};
return useQuery(query, options);
}
20 changes: 15 additions & 5 deletions packages/mst-query/tests/mstQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -709,22 +709,32 @@ test('subscription query', async () => {
expect(q.subscriptionQuery.data?.count).toBe(5);
});

test('volatile query', () => {
const { render, q } = setup();
test('volatile query', async () => {
const { render } = setup();

const text = 'testing';

let renders = 0;
const Comp = observer(() => {
const { query, data } = useVolatileQuery({
async endpoint() {
return { testing: 'testing' };
request: { data: text },
async endpoint({ request }) {
return { testing: request.data };
},
});
renders++;
if (!data) {
return null;
}
return <div>{data.testing}</div>;
});

render(<Comp />);
const { findByText } = render(<Comp />);
await wait(0);

await findByText(text);

expect(renders).toBe(3);
});

test('request with optional values', async () => {
Expand Down

0 comments on commit e282801

Please sign in to comment.