You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何封装自定义TanStack useMutation以自动传递额外数据?

封装自动注入额外数据的自定义useMutation

核心思路

通过封装TanStack的useMutation,在内部自动从Zustand store中获取需要的全局数据(如userId),并注入到每个mutation的请求参数中,避免重复手动添加。


步骤1:实现自定义Hook

创建一个通用的包裹Hook,负责处理数据注入逻辑:

import { useMutation, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
import { useAuthStore } from '../stores/authStore'; // 替换为你的Zustand store路径

// 定义需要自动注入的全局数据类型
type InjectedGlobalData = {
  userId: string;
  // 后续可扩展:tenantId、appVersion等其他全局字段
};

// 自定义Hook,兼容原useMutation的所有参数,自动注入全局数据
function useAutoInjectMutation<
  TData = unknown,
  TError = unknown,
  TBizVariables = unknown,
  TContext = unknown
>(
  options: Omit<UseMutationOptions<TData, TError, TBizVariables & InjectedGlobalData, TContext>, 'mutationFn'> & {
    mutationFn: (variables: TBizVariables & InjectedGlobalData) => Promise<TData>;
  }
): UseMutationResult<TData, TError, TBizVariables, TContext> {
  // 从Zustand获取全局数据
  const { userId } = useAuthStore(state => ({ userId: state.userId }));

  return useMutation({
    ...options,
    // 包裹原始mutationFn,合并业务参数与全局数据
    mutationFn: (bizVariables: TBizVariables) => {
      const mergedParams = {
        ...bizVariables,
        userId,
        // 后续新增全局字段直接在这里添加即可
      };
      return options.mutationFn(mergedParams);
    },
  });
}

步骤2:改造业务Hook

用自定义Hook替代原useMutation,无需再手动处理全局数据:

// 改造前(手动添加userId)
// function useUpdateRwStations() {
//   const userId = useAuthStore(state => state.userId);
//   return useMutation({
//     mutationFn: (data: { id: string; name: string }) => updateRwStationsQuery({ ...data, userId })
//   });
// }

// 改造后(自动注入userId)
function useUpdateRwStations() {
  return useAutoInjectMutation({
    mutationFn: (data: { id: string; name: string; userId: string }) => updateRwStationsQuery(data)
  });
}

// 新增的add请求同理
function useAddRwStations() {
  return useAutoInjectMutation({
    mutationFn: (data: { name: string; location: string; userId: string }) => addRwStationsQuery(data)
  });
}

步骤3:调用业务Hook

调用时只需传入业务参数,全局数据会自动注入:

const updateMutation = useUpdateRwStations();

// 仅传递业务数据,userId自动注入
updateMutation.mutate({ id: 'station_001', name: 'Updated Station Name' });

扩展说明

后续需要新增其他全局注入字段时,只需两步:

  1. 在InjectedGlobalData类型中添加新字段定义;
  2. 在自定义Hook中从Zustand获取对应值并加入mergedParams。
    所有使用useAutoInjectMutation的业务Hook都会自动带上新字段,无需逐个修改。

内容的提问来源于stack exchange,提问作者Александр Кос

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:03:19