reactjs 在使用useQuery的自定义React挂接中使用条件

gv8xihay  于 2023-02-22  发布在  React
关注(0)|答案(2)|浏览(119)

我有一个自定义的react钩子,它是用来通过发送POST请求来获取用户数据的。我想让我的自定义react钩子检查传入钩子的参数是否满足某些条件,但是我知道我不能使用钩子的条件。有人知道如何改进我的代码,以便我可以检查参数是否有效吗?

...
import { useQuery } from "@tanstack/react-query";

export const useLiquidityPositions = (userAddress: string): GraphQLResponse<LiquidityPositions> => {
    const {
        status: status,
        isLoading: loading,
        error: error,
        data: response,
    } = useQuery({
        queryKey: ["USER_POSITIONS", userAddress],
        queryFn: async () => {
            if (!isAddress(userAddress)) {
                return undefined
            }
            const res = await getLiquidityPositionsData(userAddress);
            return res;
    }});
    const payload = response?.data;

    return { status, loading, error, response, payload }
}
8ehkhllq

8ehkhllq1#

使用react-query验证查询的两种方法。

1.仅验证单个请求。https://react-query-v3.tanstack.com/guides/dependent-queries

import { useQuery } from "@tanstack/react-query";

export const useLiquidityPositions = (userAddress: string): GraphQLResponse<LiquidityPositions> => {
    const {
        status: status,
        isLoading: loading,
        error: error,
        data: response,
    } = useQuery({
        queryKey: ["USER_POSITIONS", userAddress],
        queryFn: ()=>getLiquidityPositionsData(userAddress),
          // The query will not execute until isAddress(userAddress) is true.
        enabled: isAddress(userAddress)
        });
    const payload = response?.data;

    return { status, loading, error, response, payload }
}

2.验证所有请求。https://react-query-v3.tanstack.com/guides/query-invalidation

将验证函数添加到queryClient

const queryClient = new QueryClient()
queryClient.invalidateQueries({
  predicate: query =>
    query.queryKey[0] === 'USER_POSITIONS' && isAddress(query.queryKey[1]) ,
})

<QueryClientProvider client={queryClient}>
</QueryClientProvider>
xwbd5t1u

xwbd5t1u2#

您可以根据条件启用或禁用useQuery
像这样:

export const useLiquidityPositions = (
  userAddress: string,
  enabled: boolean
): GraphQLResponse<LiquidityPositions> => {
  const {
    status: status,
    isLoading: loading,
    error: error,
    data: response,
  } = useQuery({
    queryKey: ['USER_POSITIONS', userAddress],
    queryFn: async () => {
      if (!isAddress(userAddress)) {
        return undefined;
      }
      const res = await getLiquidityPositionsData(userAddress);
      return res;
    },
    enabled,
  });
  const payload = response?.data;

  return { status, loading, error, response, payload };
};

使用时:

const result = useLiquidityPositions('...',true //your condition )

相关问题