Kiran
Kiran

Reputation: 373

How to pass params in React Query with custom hook?

I am using react query with a custom hook. I am unsure if the implementation is right and want some suggestions.

This is my custom hook:

export const useMutationQuery = (
    { url, params = {} },
    options,
) => {
    return useMutation(() => createMutation({ url, params }), options);
};

and I am using the custom hook like this

  const { mutate } = useMutationQuery({
    url: 'url',
    params: data,
  });

It all works perfectly fine but when I call the mutate function I can't pass any params. e.g.: mutate(data) instead of giving the params inside the useMutationQuery.

The problem is that a lot of times I am triggering the mutate function based on the data change which I feel is very bad.

Can someone suggest to me how can I use the mutate function like this mutate(data), with my custom hook?

Upvotes: 1

Views: 3681

Answers (1)

TkDodo
TkDodo

Reputation: 28793

the mutate function itself can also take parameters. I would only pass static things to useMutation, and dynamic things that you don't know upfront, like data that the user inputs, via mutate:

export const useMutationQuery = (
    { url },
    options,
) => {
    return useMutation((params) => createMutation({ url, params }), options);
};

in the component:

function Component() {
  const { mutate } = useMutationQuery({
    url: 'url',
  });

  return (
    <MyForm onSubmit={data => mutate(data)} />
  )
}

Upvotes: 1

Related Questions