【问题标题】:React-query and Typescript - how to properly type a mutation result?React-query 和 Typescript - 如何正确输入突变结果?
【发布时间】:2021-11-05 13:50:31
【问题描述】:

我有一个简单的钩子,将 axios 调用包装在 React Query 中:

function useInviteTeamMember(
  onSuccess?: Handler,
  onError?: Handler,
): UseMutationResult<User> {
  const mutation = useMutation(
    (payload: InviteMutationVars) => {
      return postInviteTeamMember(payload);
    },
    {
      onSuccess: (data) => {
    ...

我遇到的问题是,根据上面的定义,您希望结果是 User 类型。 即使在那个 onSuccess 处理程序(数据)中也是根据用户类型的智能感知。 但事实并非如此。 要获取实际的用户对象,我必须执行 data['data']。

我认为实际的 post 函数是根本原因,因为它键入了 Promise :

export function postInviteTeamMember(payload: InviteMutationVars): Promise<User> {
  return client.post('/user/invite/team', payload);
}

那么我怎样才能重写这段代码,使“数据”的类型正确呢?

【问题讨论】:

    标签: reactjs typescript axios react-query


    【解决方案1】:

    如果您在突变函数中键入返回对象,打字稿将在 onSuccess 参数上显示该类型。

    让我们创建一个类别作为示例。

    这里我们有突变函数,我们将返回作为一个对象键入,键为category,值类型为ExampleCategoryT。 Typescript 会知道这个函数的返回类型为: Promise&lt; ExampleCategoryT&gt;,因此无需显式编写它(当然,如果你愿意,也可以编写)。

    export async function createCategory(category: CreateCategoryArg) {
      const { data } = await http.post<{ category: ExampleCategoryT }>(
        '/categories',
        { category }
      );
    
      return data.category;
    }
    

    在 useMutation 函数中,category 参数的类型为ExampleCategoryT

    const { mutate: createCategoryMutation } = useMutation(
      createCategory,
      {
        onSuccess: (category) => {
          queryClient.setQueryData<ExampleCategoryT[]>(
            ['categories'],
            (oldData = [) => [...oldData, category]
          );
       },
       onError: (error) => {
         // ...
        },
      }
    );
    

    【讨论】:

      【解决方案2】:

      您可以自己转换响应:

      export function postInviteTeamMember(payload: InviteMutationVars): Promise<User> {
        return client.post('/user/invite/team', payload).then(response => response.data);
      }
      

      【讨论】:

      • 谢谢,但是如果响应错误,那不会有效地“吞下”错误信息而不将其返回给钩子。所以 ReactQuery 将无法访问它来处理 onError(error...) 之类的事情?
      • @rmcshry 一点也不。如果响应错误,then 块将不会运行,您需要捕获错误。
      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 2018-09-01
      • 2021-12-07
      • 2017-06-17
      • 2020-12-16
      • 1970-01-01
      • 2021-04-14
      • 2021-08-22
      相关资源
      最近更新 更多