react query. 如何在GET请求中获取响应?我只在第二次提交后才收到。

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

react query. How get response on get request? I get only after second submit

问题

我正在创建一个搜索组件。我在请求中指定一个名称,然后得到一个响应并立即显示它。

在第一次提交输入后,响应中出现未定义,但在第二次提交后,我得到了我想要的结果。

我使用了React Query的useMutation钩子,React Hook Form的useForm,axios和M-UI。

useMutation钩子的profile.mutation.ts文件如下:

import { getUsersList } from '@/services/profileService/profileService'
import { IGetUsersList } from '@/services/types'

const profileConfig = {
  getUsersList: {
    key: 'getUsersList',
    request: async (pageable: IGetUsersList) => {
      const response = await getUsersList(pageable)
      return response.data
    },
  },
}

export const useGetUsersListMutation = () => {
  const { getUsersList: config } = profileConfig
  const state = useMutation(config.request, {
    retry: 10,
    retryDelay: 1000,
    onError(error) {
      console.log('search error', error)
    },
  })
  return state
}

带有问题的Search.tsx组件如下:

import React from 'react'
import InnerSearch from '@/components/search/InnerSearch'
import SettingsSVG from '@/assets/icons/Settings.svg'
import { Box, Container } from '@mui/material'
import { IGetUsersList } from '@/services/types'
import { useForm } from 'react-hook-form'
import { useGetUsersListMutation } from '@/query/profile/profile.mutation'

const Search = () => {
  const { register, handleSubmit } = useForm<IGetUsersList>()
  const { mutateAsync: mutateGetUsersList, isSuccess, data: resData } = useGetUsersListMutation()

  const onSubmit = (requestData: IGetUsersList) => {

    console.log(requestData); // 总是没有问题

    mutateGetUsersList(requestData)

    console.log('isSuccess', isSuccess); // 在第一次提交时:isSuccess为false,在第二次提交时:isSuccess为true

    console.log('resData', resData); // 在第一次提交时:resData,在第二次提交时:resData为'right request'

  };

  return (
    <Container disableGutters sx={{ padding: '0px 10px 0px 10px', }}>
      <Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 4 }}>
        <InnerSearch register={register}
          handleSubmit={handleSubmit}
          onSubmit={onSubmit} />
        <SettingsSVG />
      </Box>
    </Container>
  )
}

export default Search

(InnerSearch组件包括:输入框和提交按钮)

我尝试使用async/await的onSubmit函数。

尝试在mutation中添加:

retry: 10,
retryDelay: 1000,

我尝试创建一个状态:

const [userlistArray, setUserlistArray] = useState([])
mutateGetUsersList(requestData).then((res) => { setUserlistArray(res) })

但是如果我执行console.log,然后在then中得到了正确的结果!但是userlistArray是未定义的。再次说明,在第二次提交时一切都正常。

更新:感谢您的帮助!(我还需要添加状态)我的结果如下:

const Search = () => {
  const [userlistArray, setUserlistArray] = useState([])

  const { register, handleSubmit } = useForm<IGetUsersList>()
  const { mutateAsync: mutateGetUsersList, data: resData } = useGetUsersListMutation()

  const onSubmit = (requestData: IGetUsersList) => {
    mutateGetUsersList(requestData)
  };

  useEffect(() => {
    setUserlistArray(resData && resData.content)
  }, [resData])

  console.log('userlistArray____', userlistArray); //现在可以工作了!

  return (
    <Container></Container>
  )
}

export default Search
英文:

I am making a search component. I specify a name in the request, I get a response and immediately display it.

After the first input submit I get undefined in response, but after the second submit a get what I wanted.

I use react query -&gt; useMutation hook, react-hook-form -&gt; useForm, axios, M-UI

hook useMutation profile.mutation.ts:

import { getUsersList } from &#39;@/services/profileService/profileService&#39;
import { IGetUsersList } from &#39;@/services/types&#39;

const profileConfig = {
  getUsersList: {
    key: &#39;getUsersList&#39;,
    request: async (pageable: IGetUsersList) =&gt; {
      const response = await getUsersList(pageable)
      return response.data
    },
  },
}

export const useGetUsersListMutation = () =&gt; {
  const { getUsersList: config } = profileConfig
  const state = useMutation(config.request, {
    retry: 10,
    retryDelay: 1000,
    onError(error) {
      console.log(&#39;search error&#39;, error)
    },
  })
  return state
}

component Search.tsx with bug:

import React from &#39;react&#39;
import InnerSearch from &#39;@/components/search/InnerSearch&#39;
import SettingsSVG from &#39;@/assets/icons/Settings.svg&#39;
import { Box, Container } from &#39;@mui/material&#39;
import { IGetUsersList } from &#39;@/services/types&#39;
import { useForm } from &#39;react-hook-form&#39;
import { useGetUsersListMutation } from &#39;@/query/profile/profile.mutation&#39;

const Search = () =&gt; {
  const { register, handleSubmit } = useForm&lt;IGetUsersList&gt;();
  const { mutateAsync: mutateGetUsersList, isSuccess, data: resData } = useGetUsersListMutation();

  const onSubmit = (requestData: IGetUsersList) =&gt; {

    console.log(requestData); //Object { username: &quot;A&quot; }   always no problem

    mutateGetUsersList(requestData)

    console.log(&#39;isSuccess&#39;, isSuccess); //on first submit: isSuccess false, on second submit: isSuccess true

    console.log(&#39;resData&#39;, resData); //on first submit: resData on second submit: resData &#39;right request&#39;

  };

  return (
    &lt;Container disableGutters sx={{ padding: &#39;0px 10px 0px 10px&#39;, }} &gt;
      &lt;Box sx={{ display: &#39;flex&#39;, flexDirection: &#39;row&#39;, alignItems: &#39;center&#39;, gap: 4 }}&gt;
        &lt;InnerSearch register={register}
          handleSubmit={handleSubmit}
          onSubmit={onSubmit} /&gt;
        &lt;SettingsSVG /&gt;
      &lt;/Box&gt;
    &lt;/Container&gt;
  )
}

export default Search

(component InnerSearch include: input and submit button)

I tried using onSubmit function acync&await.

tried add in mutation:

    retry: 10,
    retryDelay: 1000,

I tried to make a state:

const [userlistArray, setUserlistArray] = useState([])
mutateGetUsersList(requestData).then((res)=&gt;{setUserlistArray(res)})

But if I execute console.log, then I get the correct result in then! But userlistArray is undefined. again, in the second submit everything is in order.

upd. Thank you for help! (Also I needed add state) My result:

const Search = () =&gt; {
  const [userlistArray, setUserlistArray] = useState([])

  const { register, handleSubmit } = useForm&lt;IGetUsersList&gt;();
  const { mutateAsync: mutateGetUsersList, data: resData } = useGetUsersListMutation();

  const onSubmit = (requestData: IGetUsersList) =&gt; {
    mutateGetUsersList(requestData)
  };

  useEffect(()=&gt;{
		setUserlistArray(resData &amp;&amp; resData.content);
	}, [resData])


  console.log(&#39;userlistArray____&#39;, userlistArray); //now it&#39;s work!

  return (
    &lt;Container&gt;&lt;/Container&gt;
  )
}

export default Search

答案1

得分: 2

'isSuccess' 和 'resData' 不会立即更新的原因是由于 useMutation 钩子本身的异步性质。useMutation 是异步的,因此在 mutateAsync 调用后的同一 onSubmit 函数中直接记录日志时,isSuccess 和 resData 不会及时更新。

你应该依赖 useMutation 的 onSuccess 回调来处理实际可用时的数据,并使用 React Query 的状态标志(isLoading、isSuccess、isError 等)来处理界面更改。

export const useGetUsersListMutation = () => {
  const { getUsersList: config } = profileConfig;
  const state = useMutation(config.request, {
    retry: 10,
    retryDelay: 1000,
    onError(error) {
      console.log('search error', error);
    },
    // 添加此部分来处理成功
    onSuccess(data) {
      console.log('resData', data);
    }
  });
  return state;
}

const onSubmit = (requestData: IGetUsersList) => {
    console.log(requestData);
    mutateGetUsersList(requestData);
    // 这里删除了控制台日志,因为isSuccess和resData尚未更新
};
英文:

The reason why 'isSuccess' and 'resData' are not immediately updated is due to the nature of the useMutation hook itself. useMutation is asynchronous, and thus isSuccess and resData will not be updated in time to be logged directly after the mutateAsync call within the same onSubmit function.

You should instead rely on the onSuccess callback of useMutation to handle the data when it is actually available, and React Query's status flags (isLoading, isSuccess, isError, etc.) to handle UI changes.

export const useGetUsersListMutation = () =&gt; {
  const { getUsersList: config } = profileConfig
  const state = useMutation(config.request, {
    retry: 10,
    retryDelay: 1000,
    onError(error) {
      console.log(&#39;search error&#39;, error)
    },
    // add this to handle success
    onSuccess(data) {
      console.log(&#39;resData&#39;, data);
    }
  })
  return state
}

const onSubmit = (requestData: IGetUsersList) =&gt; {
    console.log(requestData);
    mutateGetUsersList(requestData);
    // removed console logs here because isSuccess and resData are not updated yet
};

答案2

得分: 1

RiQts 的答案是正确的,由于请求是异步的,控制台日志不会立即显示结果。然而一旦请求成功响应,resData 应该会触发组件的重新渲染,因此在 Search 函数中的控制台日志会显示无需再次触发突变,而是在请求成功完成后填充数据。

部分重现并运行的示例:https://codesandbox.io/s/zen-sunset-8r5389?file=/src/index.js

const Search = () => {
  const { register, handleSubmit } = useForm<IGetUsersList>();
  const { mutateAsync: mutateGetUsersList, isSuccess, data: resData } = useGetUsersListMutation();

  const onSubmit = (requestData: IGetUsersList) => {

    console.log(requestData); //Object { username: "A" }   总是没有问题

    mutateGetUsersList(requestData)
  };

  // isSuccess 和 resData 应该在成功后自动更新
  console.log('isSuccess', isSuccess); 
  console.log('resData', resData);

  return (
    <Container disableGutters sx={{ padding: '0px 10px 0px 10px' }}>
      <Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 4 }}>
        <InnerSearch register={register}
          handleSubmit={handleSubmit}
          onSubmit={onSubmit} />
        <SettingsSVG />
      </Box>
    </Container>
  )
}

编辑:我知道我有点跑题了,但这是另一种编写突变钩子的方法,使用状态来管理触发 useQuery,无论如何看起来都不错。

const Search = () => {
  // 将此状态传播到需要userListData的任何组件
  const [searchQueryData, setSearchQueryData] = useState<IGetUserList>(null);

  const { isSuccess, data: resData } = useGetUsersListQuery(searchQueryData);

  // ... 更新表单中的 searchQueryData 以重新获取
  return (
    // ...
  );
}

const useGetUsersListQuery = (searchQueryData) => {
  return useQuery({
    queryKey: ['profilesList', searchQueryData],
    queryFn: async () => { const response = await getUsersList(searchQueryData); return response.data; },
    keepPreviousData: true,
    enabled: searchQueryData !== null,
  });
};
英文:

RiQts answer is correct in that due to the requests asynchrony the console logs do not immediately show the result. However once the request responses successfully resData should trigger a re-render of the component, so console logging in the Search function should show that there is no need to trigger the mutation again but that the data gets filled after the request successfully finishes

Somewhat reproduced and working https://codesandbox.io/s/zen-sunset-8r5389?file=/src/index.js

const Search = () =&gt; {
  const { register, handleSubmit } = useForm&lt;IGetUsersList&gt;();
  const { mutateAsync: mutateGetUsersList, isSuccess, data: resData } = useGetUsersListMutation();

  const onSubmit = (requestData: IGetUsersList) =&gt; {

    console.log(requestData); //Object { username: &quot;A&quot; }   always no problem

    mutateGetUsersList(requestData)
  };

  // isSuccess and resData should automatically update after success
  console.log(&#39;isSuccess&#39;, isSuccess); 
  console.log(&#39;resData&#39;, resData);

  return (
    &lt;Container disableGutters sx={{ padding: &#39;0px 10px 0px 10px&#39;, }} &gt;
      &lt;Box sx={{ display: &#39;flex&#39;, flexDirection: &#39;row&#39;, alignItems: &#39;center&#39;, gap: 4 }}&gt;
        &lt;InnerSearch register={register}
          handleSubmit={handleSubmit}
          onSubmit={onSubmit} /&gt;
        &lt;SettingsSVG /&gt;
      &lt;/Box&gt;
    &lt;/Container&gt;
  )
}

Edit: I know I'm a bit off topic here, but here is an alternate way to write the mutation hook, use a state to manage the triggering of the useQuery, anyway just my two cents. Looking good in any case

const Search = () =&gt; {
  // spread this state to any component that needs the userListData
  const [searchQueryData, setSearchQueryData] = useState&lt;IGetUserList&gt;(null);

  const { isSuccess, data: resData } = useGetUsersListQuery(serchQueryData);

  // ... update the searchQueryData in the form to refetch
  return (
    // ...
  );
}

const useGetUsersListQuery = (serchQueryData) =&gt; {
  return useQuery({
    queryKey: [&#39;profilesList&#39;, serchQueryData],
    queryFn: async () =&gt; { const response = await getUsersList(searchQueryData); return response.data; },
    keepPreviousData: true,
    enabled: searchQueryData !== null,
  });
};

huangapple
  • 本文由 发表于 2023年7月23日 18:36:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747778.html
匿名

发表评论

匿名网友

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

确定