Skip to content

feat: Working prototype of deferred queries, but with an annoying caveat #7

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,6 @@ dist
# TernJS port file
.tern-port

.DS_Store
.DS_Store

deploy.mjs
50 changes: 50 additions & 0 deletions src/createLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,55 @@ export const createUseLoader = <
const createdQueries = createUseLoaderArgs.queries(...args);
const aggregatedQuery = aggregateToQuery(createdQueries);

if (createUseLoaderArgs.deferred) {
const createResponse = <T>(
res: T
): Types.UseQueryResult<T> => ({
data: res,
error: undefined,
isFetching: false,
isLoading: false,
isUninitialized: false,
isSuccess: true,
isError: false,
refetch: () => {},
});

const deferredQueries =
createUseLoaderArgs.deferred(createResponse);
const joinedCreatedQueries: Types.UseQueryResult<unknown>[] =
[...createdQueries];
deferredQueries.forEach((query, index) => {
if (query && createdQueries[index].isLoading) {
// We have a fallback value, and the query is loading.
joinedCreatedQueries[index] = query;
}
});
console.log(joinedCreatedQueries.map((q) => q?.isLoading));
const aggregatedDeferredQuery = aggregateToQuery(
joinedCreatedQueries
);
console.log(
"Aggregated state",
aggregatedDeferredQuery.isLoading
);

if (aggregatedDeferredQuery.isSuccess) {
const data = createUseLoaderArgs.transform
? createUseLoaderArgs.transform(
joinedCreatedQueries as unknown as Types.MakeDataRequired<QRU>
)
: joinedCreatedQueries;

return {
...aggregatedDeferredQuery,
data,
currentData: data,
originalArgs: args,
} as Types.UseQueryResult<R>;
}
} // end deferred handling

if (aggregatedQuery.isSuccess) {
const data = createUseLoaderArgs.transform
? createUseLoaderArgs.transform(
Expand Down Expand Up @@ -45,6 +94,7 @@ export const createLoader = <
queries:
createLoaderArgs.queries ?? (() => [] as unknown as QRU),
transform: createLoaderArgs.transform,
deferred: createLoaderArgs.deferred,
});

const loader: Types.Loader<P, R, QRU, A> = {
Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ export type CreateUseLoaderArgs<
queries: (...args: OptionalGenericArg<A>) => QRU;
/** Transforms the output of the queries */
transform?: LoaderTransformFunction<QRU, R>;
deferred?: (
createResponse: <CR>(val: CR) => UseQueryResult<CR>
) => readonly (UseQueryResult<unknown> | undefined)[];
defer?: number[];
fallback?: unknown[];
};

export type UseLoader<A, R> = (
Expand Down
2 changes: 1 addition & 1 deletion testing-app/src/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const handlers = [
}),
rest.get("/pokemon/:name", (req, res, c) => {
if (req.params.name === "error") {
return res(c.delay(RESPONSE_DELAY), c.status(500));
return res(c.delay(RESPONSE_DELAY + 500), c.status(500));
}
return res(
c.delay(RESPONSE_DELAY),
Expand Down
72 changes: 72 additions & 0 deletions testing-app/src/tests.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,78 @@ describe("withLoader", () => {
);
});

test("Can defer one of two queries", async () => {
const loader = createLoader({
queries: () => {
// Queries that are not deferred should be called first
const notDeferred = useGetPokemonsQuery(undefined);
const notDeferred2 = useGetPokemonsQuery(undefined);
// Queries that are deferred should be called last
const deferred = useGetPokemonByNameQuery("charizard");
return [
notDeferred2,
notDeferred,
deferred, // 100ms slower than useGetPokemonsQuery
] as const;
},
deferred: (cr) => [
undefined,
undefined,
cr({ name: "temp-charizard" }),
],
onLoading: () => <div>Loading</div>,
});

const Component = withLoader(
(_, loaderData) => (
<>
<div>{loaderData[2].data.name}</div>
</>
),
loader
);
render(<Component />);
expect(screen.getByText("Loading")).toBeVisible();
await waitFor(() =>
expect(screen.getByText("temp-charizard")).toBeVisible()
);
await waitFor(() =>
expect(screen.getByText("charizard")).toBeVisible()
);
});

test("Can defer all queries", async () => {
const loader = createLoader({
queries: () =>
[
useGetPokemonsQuery(undefined),
useGetPokemonByNameQuery("charizard"),
] as const,
deferred: (cr) => [
cr({ results: [] }),
cr({ name: "temp-charizard" }),
],
onLoading: () => <div>Loading</div>,
});
const Component = withLoader(
(_, loaderData) => (
<>
<div>{loaderData[1].data.name}</div>
<div>{loaderData[0]?.data ? "Loaded" : "💩"}</div>
</>
),
loader
);
render(<Component />);

expect(screen.getByText("temp-charizard")).toBeVisible();
expect(screen.getByText("Loaded")).toBeVisible();

await waitFor(() =>
expect(screen.getByText("charizard")).toBeVisible()
);
});

describe(".extend()", () => {
test("Can extend onLoading", async () => {
render(<ExtendedLoaderComponent />);
Expand Down