HuolalaTech / react-query-kit

🕊️ A toolkit for ReactQuery that make ReactQuery hooks reusable and typesafe
MIT License
355 stars 11 forks source link

how add token inside `useDefaultOptions` in `createMutation` #17

Closed renzoyyan closed 1 year ago

renzoyyan commented 1 year ago

How can I add token inside useDefaultOptions ? I tried to do it same with createQuery but got error.

export const useCreatePost = createMutation<TPost, TCreatePostVariables, ApiServiceError>({
  mutationFn: (variables) => post.createPost(variables.payload, variables.authToken),

  useDefaultOptions: () => {
    const {authToken} = useAuth()

    return {};
  },
})
liaoliao666 commented 1 year ago

can u provide me a codesandbox example?

renzoyyan commented 1 year ago

can u provide me a codesandbox example?

https://codesandbox.io/p/sandbox/nostalgic-snowflake-mvpz3j @liaoliao666 sorry for late reply

liaoliao666 commented 1 year ago

I got ur mean. But the createMutation function that do not support option variables. u can only using mutate to implement like below

const useCreatePost = createMutation<
  any,
  TCreatePostVariables,
  ApiServiceError
>({
  mutationFn: variables =>
    fetch('/post/new', {
      method: 'POST',
      body: JSON.stringify(variables.payload),
      headers: {
        Authorization: `Bearer ${variables.accessToken}`,
      },
    }),
})

function App() {
  const { mutate } = useCreatePost()
  const { accessToken } = useAuth()

  return (
    <button
      onClick={() => {
        mutate({ accessToken })
      }}
    >
      create post
    </button>
  )
}

Or maybe u should using a external store to store ur auth value(eg. zustand or jotai). It's a convenience way to use. as shown below

const auth = { accessToken: "" }

const useCreatePost = createMutation<
  any,
  TCreatePostVariables,
  ApiServiceError
>({
  mutationFn: variables =>
    fetch('/post/new', {
      method: 'POST',
      body: JSON.stringify(variables.payload),
      headers: {
        Authorization: `Bearer ${auth.accessToken}`,
      },
    }),
})
liaoliao666 commented 1 year ago

https://github.com/liaoliao666/react-query-kit/issues/18 fixed this issue Variables from useDefaultOptions are not passed to queryFn in v1.4.3