TanStackT
TanStack2y ago
10 replies
full-green

Default Mutation Function best practices and Typescript

I've set up a default query function per the guide in the docs, but there's no guide on a default mutation function. I'd like to set on up so I don't have to get the auth token in each component, etc. Can I just do the following:

type MyMutationFunctionProps = {
  apiPath: string
  variables: object
}

const defaultMutationFn = async ({ apiPath, variables }: MyMutationFunctionProps) => {
  console.log('defaultMutationFn', variables)
  const { data } = await axios.post(`${BASE_URL}/${apiPath}`, variables, {
    headers: { Authorization: `Bearer ${useAppState.getState().token}` },
  })
  return data
}


If that's appropriate, how do I resolve the defaultOptions.mutations.mutationFn typescript error?
Type '({ apiPath, variables }: MyMutationFunctionProps) => Promise<any>' is not assignable to type 'MutationFunction<unknown, unknown>'.
  Types of parameters '__0' and 'variables' are incompatible.
    Type 'unknown' is not assignable to type 'MyMutationFunctionProps'.ts(2322)
(property) MutationOptions<unknown, Error, unknown, unknown>.mutationFn?: MutationFunction<unknown, unknown> | undefined
Was this page helpful?