Hildebrandt Tobias
04/22/2025, 1:45 PMval submitHandler = useMutation<CompanyDto?, Error, String, Unit>(
options = UseMutationOptions(
mutationFn = {
secureApi(CompanyEndpoints.putCompany.copy(
bodySerializerType = typeOf<CompanyDto>(),
body = editedCompany
))
},
onSuccess = { _, _, _ ->
queryClient.invalidateQueries(
InvalidateQueryFilters<Any,Any,Any, QueryKey>(
queryKey = ADMIN_QUERY_KEY
)
)
}
)
)
I kind of hoped the types of InvalidateQueryFilters
were inferable from useMutation<...>
.
Or am I using it wrong? (Trying to follow this: https://tanstack.com/query/latest/docs/framework/react/examples/auto-refetching?panel=sandbox)turansky
04/22/2025, 7:43 PMturansky
04/22/2025, 7:45 PMturansky
04/22/2025, 7:46 PMval handler = useMyMutation(ADMIN_QUERY_KEY) {
secureApi(CompanyEndpoints.putCompany.copy(
bodySerializerType = typeOf<CompanyDto>(),
body = editedCompany
))
}
Hildebrandt Tobias
04/22/2025, 8:05 PMturansky
04/22/2025, 8:18 PMuseQuery
, useMutation
are very generic hooks.
Usually you don't use such hooks directly.Hildebrandt Tobias
04/23/2025, 2:06 PMfun <T>useQuery(
queryKey: QueryKey,
initialData: T? = null,
queryFunction: () -> PromiseResult<T?>
): UseQueryResult<T, Error> =
useQuery<T?, Error, T, QueryKey>(
options = UseQueryOptions(
queryKey = queryKey,
initialData = initialData?.let { {initialData} },
queryFn = QueryFunction { queryFunction() }
)
)
fun <T>useMutation(
mutateFunction: (String) -> Promise<T>,
onSuccess: QueryClient.(T) -> Promise<*>,
): UseMutationResult<T, Error, String, Unit> =
with(useQueryClient()) {
useMutation<T, Error, String, Unit>(
options = UseMutationOptions(
mutationFn = mutateFunction,
onSuccess = { data, _, _ ->
onSuccess(data)
}
)
)
}
fun <T>UseMutationResult<T, Error, String, Unit>.mutate(block: (T) -> Unit) =
mutate("", MutateOptions(
onSuccess = { data, _, _ ->
block(data)
}
))
fun QueryClient.invalidateQueryKey(queryKey: QueryKey): Promise<*> =
invalidateQueries(
InvalidateQueryFilters<Any,Any,Any, QueryKey>(
queryKey = queryKey
)
)
And how I use it:
val companyQuery = useQuery(ADMIN_QUERY_KEY, loaderData) {
secureApi(CompanyEndpoints.getCompany)
}
val handleSubmit = useMutation(
mutateFunction = { secureApi(CompanyEndpoints.putCompany.copy(
bodySerializerType = typeOf<CompanyDto>(),
body = editedCompany
))},
onSuccess = {
invalidateQueryKey(queryKey = ADMIN_QUERY_KEY)
}
)
[...]
Button {
variant = ButtonVariant.contained
color = ButtonColor.primary
onClick = { handleSubmit.mutate {
handleGoBack()
}}
disabled = company.name.isEmpty()
+"save".intl()
}