tramvaijs/tramvai

How can I access dependencies inside mutationOptions in createMutation

andryxxa93 opened this issue · 3 comments

Hello! There is a problem - I want to access the queryClient object inside onSuccess in mutationOptions createMutation. Added via QUERY_CLIENT_TOKEN depending. But inside onSuccess, deps cannot be accessed through this.deps.

export const postReviewCommentMutation = createMutation({
  key: 'postReviewComment',
  async fn(_, { reviewId, text }: TPostReviewCommentBody) {
    const { api, apiErrorHandlerFactory, queryClient } = this.deps;
    const apiErrorHandler = apiErrorHandlerFactory();

    const postReviewComment = api.postReviewComment({ text }, reviewId, {
      signal: this.abortSignal,
    });

    postReviewComment.catch(apiErrorHandler);
    return postReviewComment.then((data) => data);
  },
  mutationOptions: {
    onSuccess() {
      console.log(this.deps); // here will be undefined
    },
  },
  deps: {
    queryClient: QUERY_CLIENT_TOKEN,
    api: API_TOKEN,
    apiErrorHandlerFactory: API_ERROR_HANDLER_FACTORY_TOKEN,
  },
});

Hi!

Interesting case, I think it is possible to iterate over mutation options here, and bind ctx for all functions.

It will be perfect if you want to contribute this changes?

Hi!

Interesting case, I think it is possible to iterate over mutation options here, and bind ctx for all functions.

It will be perfect if you want to contribute this changes?

I think this is a convenient solution! Yes, it would be great if you add it. Thank you!

Contribution welcome!