1

我想从 SWR 0.22 升级到 0.55,但 useSWRPages 已被弃用,所以我将被迫使用 useSWRInfinite,但我无法理解如何重写我当前的函数以使用 useSWRInfinite。我如何重写它以使用 useSWRInfinite 来无限加载仍然受支持?

function useRecentDevices(  
  deviceId: string | undefined,
  dateFromUtc: Date | undefined,
  dateToUtc: Date,
) {
  return useSWRPages<Pick<SummaryList, 'skip' | 'take'> | null, SummaryList>(
    'devices',
    ({ offset, withSWR }) => {
      const { data } = withSWR(
        useSWR(
          ['devices/recent', deviceId, offset?.skip, offset?.take ?? DEFAULT_TAKE],
          async (
            path: string,
            deviceId: string | undefined,    
            skip: number | undefined,
            take: number,
          ) => {
            const response = await get<SummaryList>(path, {
              deviceId,
              dateFromUtc: dateFromUtc?.toISOString(),
              dateToUtc: dateToUtc.toISOString(),
              skip,
              take,
            });
            if (!response.success) {
              throw new Error('unable to fetch data');
            }
            return response.data;
          },
          { suspense: !offset },
        ),
      );

      const devices = data?.devices;
      return devices ? devices.map(order => <DeviceLine key={order.salesOrderId} {...order} />) : null;
    },
    ({ data }) => {
      const { hasMore, skip, take } = data!;

      if (hasMore) {
        return { skip: skip + take, take };
      }

      return null;
    },
    [deviceId, dateFromUtc, dateToUtc],
  );
}
4

0 回答 0