kererū
kererū
TtRPC
Created by kererū on 9/26/2023 in #❓-help
How to type a helper function to standardise loading and error states with a useQuery call?
In case it helps anyone, this seems to work
export function RenderQuery<
T extends QueryLike,
G extends InferQueryLikeInput<T>,
P extends InferQueryLikeData<T>,
>({
useQuery,
input,
render,
}: {
useQuery: T;
input: G;
render: (data: P) => ReactElement;
}) {
const query = useQuery.useQuery(input);
switch (query.status) {
case "error":
return <div>Sorry, something went wrong.</div>
case "loading":
return <LoadingSpinner />;
case "success":
return render(query.data);
default:
const _exhaustivenessCheck: never = query;
return _exhaustivenessCheck;
}
}
export function RenderQuery<
T extends QueryLike,
G extends InferQueryLikeInput<T>,
P extends InferQueryLikeData<T>,
>({
useQuery,
input,
render,
}: {
useQuery: T;
input: G;
render: (data: P) => ReactElement;
}) {
const query = useQuery.useQuery(input);
switch (query.status) {
case "error":
return <div>Sorry, something went wrong.</div>
case "loading":
return <LoadingSpinner />;
case "success":
return render(query.data);
default:
const _exhaustivenessCheck: never = query;
return _exhaustivenessCheck;
}
}
Called like
<RenderQuery
useQuery={trpc.user.details}
input={{userId}}
render={(data) => <div>{data.username}</div>} />
<RenderQuery
useQuery={trpc.user.details}
input={{userId}}
render={(data) => <div>{data.username}</div>} />
4 replies
TtRPC
Created by kererū on 7/12/2023 in #❓-help
Upgrading from tRPC v9 and NextJS v12. Should I upgrade NextJS first or tRPC?
Thank you 🙂
5 replies