1

我想将查询传递给 getAnalysisListByPatientIdApi 所以我尝试将查询放入 useInfiniteQuery 数组的第一个参数中,例如useQuery

  const { data: analyses } = useInfiniteQuery(
    ['getAnalysesByPatientIdApi', { patientId: selectedPatientId }],
    getAnalysisListByPatientIdApi,
    {
      getFetchMore: (lastGroup, allGroups) => {
        const morePagesExist = lastGroup?.data.result.contents.length === 9
        if (!morePagesExist) return false
        return allGroups.length + 1
      },
    },
  )

export const getAnalysisListByPatientIdApi = (_: string, query?: AnalysisListPatientQuery) => {
// should get query from useInfiniteQuery
  return api.post<PagingResponse<AnalysisListPatientResponse>>(`/analysis/list/patient`, {
    page: query?.page || 1,
    size: query?.size || 9,
    patientId: query?.patientId || '',
  })
}

我希望从 getAnalysisListByPatientIdApi 中的 useInfiniteQuery 获得 { patientId: selectedPatientId },但发生错误:Type '{ patientId: string; }' is not assignable to type 'string'

如何解决这个问题?有任何想法吗?

4

1 回答 1

2

耶~!我自己做的。谁想知道如何使用 useInfiniteQuery...

关键是 useInfiniteQuery 是自己将游标传递给 exampleApi。您所要做的就是实施getFetchMore

import React from "react";
import { useInfiniteQuery } from "react-query";
import { ReactQueryDevtools } from "react-query-devtools";
import axios from "./fakeApis/axios";

const exampleApi = async (_: any, cursor: number) => {
  console.log(_, cursor);
  return await await axios.post(`/list/${cursor || 1}`);
};

export function App() {
  const { canFetchMore, isLoading, error, data, fetchMore } = useInfiniteQuery(
    "repoData",
    exampleApi,
    {
      getFetchMore: (lastGroup, allGroups) => {
        let morePagesExist = true;
        if (lastGroup && lastGroup.data.result) {
          morePagesExist = lastGroup.data.result !== null;
          console.log(morePagesExist);
        }
        if (!morePagesExist) return false;
        console.log(lastGroup?.data);
        // returns next cursor which will send to the cursor of eaxmpleApi
        return lastGroup?.data?.result?.currentPageNo + 1 || false;
      }
    }
  );

  return (
    <div>
      {isLoading && <div>"Loading..."</div>}
      {error && <div>"An error has occurred: " + error.message</div>}
      <button
        disabled={!canFetchMore}
        onClick={(e) => {
          fetchMore();
        }}
      >
        fetch more
      </button>
      {data?.map((o, index) => {
        return (
          <div key={index}>
            {JSON.stringify(o?.data?.result?.contents, 0, 1)}
          </div>
        );
      })}
      <ReactQueryDevtools initialIsOpen />
    </div>
  );
}

https://codesandbox.io/s/react-query-useinfinitequery-be62c?file=/src/App.tsx

于 2020-08-13T06:26:53.403 回答