Skip to content

Instantly share code, notes, and snippets.

@ayush-seth
Created March 18, 2023 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayush-seth/772caabc4e28cc49f2bfe9232a6d9aab to your computer and use it in GitHub Desktop.
Save ayush-seth/772caabc4e28cc49f2bfe9232a6d9aab to your computer and use it in GitHub Desktop.
import { useAuth } from "@clerk/nextjs";
import { useQuery } from "@tanstack/react-query";
import { type ZodSchema } from "zod";
import { api } from "../utils";
type CreateAuthedQueryParams<TSchema> = {
queryKey: string[];
endpoint: string;
zodSchema: ZodSchema<TSchema>;
};
function createAuthedQuery<TSchema>(params: CreateAuthedQueryParams<TSchema>) {
return () => {
const { getToken } = useAuth();
const { queryKey, endpoint, zodSchema } = params;
return useQuery({
queryKey,
queryFn: async () => {
return zodSchema.parse(
await api
.get(endpoint, {
headers: {
Authorization: `Bearer ${(await getToken()) ?? ""}`,
},
})
.json()
);
},
});
};
}
export { createAuthedQuery };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment