next.js RTK查询:未调用NodeApi的合并方法

qnzebej0  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(121)

简介:
我使用createApi来设置一个端点,它将picsum pictures作为一个列表返回。由于picsum API的列表端点不提供图片的大小调整版本,我使用queryFn来欺骗它这样做(它只是更新url属性)。然后我将这个url列表传递给img标签。
使命:
我需要实现一个无限滚动器。为此,我使用了serializeQueryArgsmerge属性。我希望尽管页面发生了变化,但该高速缓存仍能保留,因为每次点击“加载更多”时,我都需要将新的结果与之合并。我已经放置了一些console.log来查看发生了什么。
picsumApi.ts

import { MaybePromise } from "@reduxjs/toolkit/dist/query/tsHelpers";
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

const BASE_URL = "https://picsum.photos";

async function tryMaybePromise(maybePromise: MaybePromise<any>) {
  const response = await maybePromise;
  if (response.error) throw response.error;
  return response.data;
}

export const picsumApi = createApi({
  reducerPath: "picsumApi",
  baseQuery: fetchBaseQuery({ baseUrl: BASE_URL }),
  endpoints: (builder) => ({
    getPictures: builder.query<
      PicsumThumbnail[],
      { page?: number; limit?: number }
    >({
      queryFn: async ({ page, limit }, _api, _opt, fetchWithBQ) => {
        console.log("queryfn");

        const picsumThumbnails = (await tryMaybePromise(
          fetchWithBQ({
            url: "v2/list",
            params: { page, limit },
          })
        )) as PicsumThumbnail[];

        for (const pi of picsumThumbnails) {
          pi.url = BASE_URL + `/id/${pi.id}/300/200`;
        }

        return { data: picsumThumbnails };
      },
      serializeQueryArgs: ({ queryArgs }) => {
        console.log("serializeQueryArgs");
        const { page, ...otherArgs } = queryArgs;
        return otherArgs;
      },
      merge: (currentCache, newItems) => {
        console.log("merge");
        currentCache.push(...newItems);
      },
    }),
    getPictureById: builder.query<PicsumThumbnail, string>({
      query: (id) => `/${id}/300/200`,
    }),
  }),
});

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetPicturesQuery, useGetPictureByIdQuery } = picsumApi;

字符串
page.tsx

"use client";
import { useGetPicturesQuery } from "@/redux/services/picsumApi";
import { Button } from "@radix-ui/themes";
import Image from "next/image";
import React, { useEffect, useState } from "react";

export default function HomePage() {
  const [page, setPage] = useState(1);
  const {
    data: pictures,
    error,
    isLoading,
  } = useGetPicturesQuery({ page, limit: 4 });

  return (
    <div>
      {pictures?.map(({ id, url }) => (
        <Image key={id} width={300} height={200} alt={String(id)} src={url} />
      ))}
      <Button
        onClick={() => {
          setPage((prevPage) => prevPage + 1);
        }}
      >
        Load more
      </Button>
    </div>
  );
}


问题:
当页面第一次加载时,我在控制台中得到“queryFn”和“serializeQueryArgs”日志。当我点击“加载更多”时,我得到“serializeQueryArgs”。但我从未收到“合并”日志。
我不知道还能尝试什么。我找不到queryFnmerge的任何示例。也许它们不兼容?我在RTK查询文档中找不到任何解释。

为什么merge方法永远不会被调用?

dwthyt8l

dwthyt8l1#

由于RTKQ通常会用新的响应替换缓存条目,因此您通常需要将其与serializeQueryArgs或forceRefetch选项一起使用,以保留现有的缓存条目,以便更新它。
文档:https://redux-toolkit.js.org/rtk-query/api/createApi

相关问题