1

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?

1 Answer 1

1

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)} />
  )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.