Created
October 5, 2024 01:43
-
-
Save thierryskoda/ec13a26f7e6fb9101d922f09889ad295 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useQuery } from "@tanstack/react-query" | |
import { queryClient } from "../../libs/react-query" | |
import { supabase } from "../../libs/supabase/supabase-client" | |
import { IUserId } from "../../types/database-custom-types" | |
import { APILogger } from "../../utils/logger" | |
export function getUserByIdQueryKey(userId: IUserId) { | |
return ["get-user-by-id-" + userId] | |
} | |
export type IUserById = Awaited<ReturnType<typeof getUserById>> | |
async function getUserById(userId: IUserId) { | |
APILogger.debug(`getUserById(${userId})`) | |
const { data: user } = await supabase | |
.from("profiles") | |
.select("*") | |
.eq("id", userId) | |
.maybeSingle() | |
.throwOnError() | |
return user | |
} | |
export function useUserById(userId: IUserId) { | |
return useQuery(getUserByIdQueryOptions(userId)) | |
} | |
export function getUserByIdQueryOptions(userId: IUserId) { | |
return { | |
queryKey: getUserByIdQueryKey(userId), | |
queryFn: () => getUserById(userId), | |
enabled: !!userId, | |
} | |
} | |
export function getUserByIdQuery(userId: IUserId) { | |
return queryClient.fetchQuery(getUserByIdQueryOptions(userId)) | |
} | |
export function refetchUserById(userId: IUserId) { | |
return queryClient.refetchQueries(getUserByIdQueryOptions(userId)) | |
} | |
export function getUserByIdLC(userId: IUserId) { | |
return queryClient.getQueryData<IUserById>(getUserByIdQueryKey(userId)) | |
} | |
export function setUserByIdInLC(user: IUserById) { | |
if (!user) { | |
APILogger.debug(`Don't have a user to set in LC in setUserInLC`) | |
return | |
} | |
return queryClient.setQueryData(getUserByIdQueryKey(user.id), user) | |
} | |
export function getOrFetchUserById(userId: IUserId) { | |
const user = getUserByIdLC(userId) | |
if (user) { | |
return Promise.resolve(user) | |
} | |
return getUserByIdQuery(userId) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment