为什么我无法访问在React Query变更中的onSuccess返回的数据?

huangapple go评论45阅读模式
英文:

Why can't I access the data returned from onSuccess in my react-query mutation?

问题

我试图理解React Query,但卡在一个特定问题上。我想要添加一个新的月度记录,并在创建时触发一个依赖过程。因此,我正在使用onSuccess,期望刚刚创建的数据被返回,但这始终是"undefined"。

以下是我的突变(mutation)代码:

import { useMutation, useQueryClient } from 'react-query';
import toast from 'react-hot-toast';

import { axiosInstance, getJWTHeader } from '../../../../api/axiosInstance';
import { queryKeys } from '../../../../react-query/constants';
import { useUser } from '../../../User/hooks/useUser';
import { useHistoryProcessing } from '../../../../hooks/useHistoryProcessing';

async function addMonth(newMonth, user) {
  if (!newMonth) return null;
  const { data } = await axiosInstance.post(
    '/months',
    { newMonth },
    { headers: getJWTHeader(user) }
  );
  return data.month;
}

export function useMonthPost() {
  const { user } = useUser();
  const { ProcessHistory } = useHistoryProcessing();
  const queryClient = useQueryClient();

  const { mutate: addNewMonth } = useMutation(
    (newMonthData) => addMonth(newMonthData, user),
    {
      onMutate: async () => {
        queryClient.cancelQueries(queryKeys.months);
      },
      onError: (error) => {
        toast(error);
      },
      onSettled: () => {
        queryClient.invalidateQueries(queryKeys.months);
      },
      onSuccess: (data) => {
        console.log(data);
        ProcessHistory(data);
      },
    }
  );
  return addNewMonth;
}

如果需要进一步的帮助,请告诉我。

英文:

I am trying to get my head round react query and can't get past a particular issue. I want to add a new month record and on creation of this, fire off a dependent process. I am therefore using onSuccess, expecting the data just created to be returned but this is always "undefined".

Here is my code for the mutation:

import { useMutation, useQueryClient } from 'react-query';
import toast from 'react-hot-toast';

import { axiosInstance, getJWTHeader } from '../../../../api/axiosInstance';
import { queryKeys } from '../../../../react-query/constants';
import { useUser } from '../../../User/hooks/useUser';
import { useHistoryProcessing } from '../../../../hooks/useHistoryProcessing';

async function addMonth(newMonth, user) {
  if (!newMonth) return null;
  const { data } = await axiosInstance.post(
    '/months',
    { newMonth },
    { headers: getJWTHeader(user) }
  );
  return data.month;
}

export function useMonthPost() {
  const { user } = useUser();
  const { ProcessHistory } = useHistoryProcessing();
  const queryClient = useQueryClient();

  const { mutate: addNewMonth } = useMutation(
    (newMonthData) => addMonth(newMonthData, user),
    {
      onMutate: async () => {
        queryClient.cancelQueries(queryKeys.months);
      },
      onError: (error) => {
        toast(error);
      },
      onSettled: () => {
        queryClient.invalidateQueries(queryKeys.months);
      },
      onSuccess: (data) => {
        console.log(data);
        ProcessHistory(data);
      },
    }
  );
  return addNewMonth;
}

答案1

得分: 1

以下是翻译好的部分:

  1. 双重检查变异配置:确保变异配置正确,并且服务器在响应中返回了新创建的数据。查看API文档或负责处理月份记录创建的代码,以确保它返回已创建的数据。

  2. 验证返回数据的结构:如果服务器响应包含嵌套数据或与预期的结构不同,直接访问数据可能无法正常工作。在这种情况下,您需要遍历响应对象以访问所需的数据。例如,如果响应对象看起来像这样:{ data: { month: { id: 1, name: 'June' } } },您将使用 response.data.month 来访问已创建的月份数据。

  3. 检查错误处理:如果在变异过程中出现任何错误,将触发 onError 回调而不是 onSuccess。确保您没有意外地处理错误情况并期望在 onSuccess 回调中获得已创建的数据。

  4. 考虑使用 async/await:如果您在 onSuccess 回调中进行异步调用以获取其他数据或执行其他操作,请确保正确处理承诺。您可以使用 async/await 或 .then() 来等待异步操作完成后再继续。

英文:

There could be a few reasons why this is happening:

  1. Double-check the mutation configuration: Make sure that the mutation is configured correctly, and the server is returning the newly created data in the response. Check the API documentation or the code responsible for handling the creation of the month record to ensure that it returns the created data.

  2. Verify the shape of the returned data: If the server response contains nested data or has a different structure than expected, accessing data directly might not work. In this case, you need to traverse the response object to access the desired data. For example, if the response object looks like { data: { month: { id: 1, name: 'June' } } }, you would access the created month data using response.data.month.

  3. Check for error handling: If there are any errors during the mutation process, the onError callback will be triggered instead of onSuccess. Make sure you're not accidentally handling the error case and expecting the created data in the onSuccess callback.

  4. Consider using async/await: If you are making an asynchronous call within the onSuccess callback to fetch additional data or perform another operation, ensure that you are handling promises correctly. You can use async/await or .then() to wait for the asynchronous operation to complete before proceeding.

答案2

得分: 1

> 我因此使用了onSuccess,期望刚刚创建的数据被返回,但它总是"undefined"。

首先,您的onSuccess回调没有返回任何内容 - 看起来缺少了一个返回语句:

onSuccess: (data) => {
  console.log(data);
  ProcessHistory(data);
},

但是第二点,onSuccess是一个事件处理程序。您可以对数据执行某些操作,但它不是用于转换数据的。这在以"onXXX"命名的函数中相当常见。

无论从mutationFn返回什么都将作为data在您的组件中可用,因此如果您想要进行后处理,请在mutationFn内部进行:

useMutation(
    async (newMonthData) => {
      const data = await addMonth(newMonthData, user)
      const processed = ProcessHistory(data)

      return processed
   }
)
英文:

> I am therefore using onSuccess, expecting the data just created to be returned but this is always "undefined".

First of all, your onSuccess callback doesn't return anything - seems like it's missing a return statement:

onSuccess: (data) => {
  console.log(data);
  ProcessHistory(data);
},

but second, onSuccess is an event handler. You can do something with data, but it's not there to transform data. This is pretty common with functions named onXXX.

Whatever is returned from the mutationFn will be available as data in your component, so if you want post-processing, do it inside the mutationFn:

useMutation(
    async (newMonthData) => {
      const data = await addMonth(newMonthData, user)
      const processed = ProcessHistory(data)

      return processed
   }
)

</details>



huangapple
  • 本文由 发表于 2023年6月1日 15:14:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76379493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定