Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | 25x 1880x 12x 26x 26x 1x 50x 50x 2x 1x 1x 17x 17x 2x 1x 1x 40x 29x 9x 41x 2x 27x 27x 3x 2x 4x | import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
createBaby,
createBabyInvite,
deleteBaby,
fetchBabies,
fetchBabyGuardians,
removeBabyGuardian,
updateBaby,
} from './babies.api'
import type { Baby, BabyFormInput, Guardian } from './babies.schemas'
export const babiesQueryKey = ['babies'] as const
/**
* Also doubles as the app's session probe (see app/routes/ProtectedLayout.tsx):
* there is no dedicated /auth/me endpoint, so a 401 here means "not logged in".
*/
export function useBabies() {
return useQuery({
queryKey: babiesQueryKey,
queryFn: fetchBabies,
})
}
/** Used by the "Add" wizards to auto-select (and hide the picker) when there's only one baby. */
export function soleBaby(babies: Baby[] | undefined): Baby | undefined {
return babies?.length === 1 ? babies[0] : undefined
}
export function useCreateBaby() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: createBaby,
onSuccess: (baby) => {
queryClient.setQueryData<Baby[]>(babiesQueryKey, (prev) => (prev ? [...prev, baby] : [baby]))
},
})
}
export function useUpdateBaby(babyId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (input: BabyFormInput) => updateBaby(babyId, input),
onSuccess: (updated) => {
queryClient.setQueryData<Baby[]>(babiesQueryKey, (prev) =>
prev?.map((baby) => (baby.id === updated.id ? updated : baby)),
)
},
})
}
export function useDeleteBaby() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (babyId: string) => deleteBaby(babyId),
onSuccess: (_data, deletedBabyId) => {
queryClient.setQueryData<Baby[]>(babiesQueryKey, (prev) =>
prev?.filter((baby) => baby.id !== deletedBabyId),
)
},
})
}
export function babyGuardiansQueryKey(babyId: string) {
return ['babies', babyId, 'guardians'] as const
}
export function useBabyGuardians(babyId: string) {
return useQuery({
queryKey: babyGuardiansQueryKey(babyId),
queryFn: () => fetchBabyGuardians(babyId),
enabled: !!babyId,
})
}
export function useCreateBabyInvite(babyId: string) {
return useMutation({
mutationFn: (inviteeEmail?: string) => createBabyInvite(babyId, inviteeEmail),
})
}
export function useRemoveBabyGuardian(babyId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (userId: string) => removeBabyGuardian(babyId, userId),
onSuccess: (_data, removedUserId) => {
queryClient.setQueryData<Guardian[]>(babyGuardiansQueryKey(babyId), (prev) =>
prev?.filter((guardian) => guardian.userId !== removedUserId),
)
},
})
}
|