T
TanStack2y ago
genetic-orange

What's a good style for organizing useMutation and fetch function types?

I'm curious how folks tend to organize the types for their mutation queries. In my experience, the mutating fetch function and the useMutation hook kind of share the same type, but expressed in different ways. For example, the fetch function might accept the entire type, and the useMutation hook might Pick pieces from the type to use in the initial call to the hook, and in the mutate function itself. Here's an example to demonstrate how I've done things in the past. It works, but it feels a bit clunky to me. I'm curious if folks have a nicer approach that they prefer?
type UserResponseObject = {
id: number
name: string
// Potentially more properties
}

type UpdateUserRequestBody = {
name: string
// Potentially more properties
}

type UpdateUserOptions = {
userId: number
body: UpdateUserRequestBody
}

const updateUser = ({ userId, body }: UpdateUserOptions): Promise<UserResponseObject> => {
return axios.patch(`/user/${userId}`, body).then((response) => response.data)
}


export const useUpdateUser = ({ userId }: Pick<UpdateUserOptions | 'userId'>) => {
return useMutation({
mutationFn: ({ body }: Pick<UpdateUserOptions | 'body'>) => updateUser({ userId, body }),
queryKey: queryKeys.user({ userId })
})
}
type UserResponseObject = {
id: number
name: string
// Potentially more properties
}

type UpdateUserRequestBody = {
name: string
// Potentially more properties
}

type UpdateUserOptions = {
userId: number
body: UpdateUserRequestBody
}

const updateUser = ({ userId, body }: UpdateUserOptions): Promise<UserResponseObject> => {
return axios.patch(`/user/${userId}`, body).then((response) => response.data)
}


export const useUpdateUser = ({ userId }: Pick<UpdateUserOptions | 'userId'>) => {
return useMutation({
mutationFn: ({ body }: Pick<UpdateUserOptions | 'body'>) => updateUser({ userId, body }),
queryKey: queryKeys.user({ userId })
})
}
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?