将数据存储到特定状态路径,同时忽略动态参数。

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

RTK Query: How store data into specific state path while ignoring dynamic parameter

问题

现在,我正在使用Redux Toolkit Query从API获取数据。但是,每次发送请求时,该API都需要在查询参数中提供一个新的签名,就像下面的代码中一样:

export const restApi = createApi({
  reducerPath: "restApi",
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/pokemon/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query({
      query: ({ name, signature }) => `${name}?signature=${signature}`
    }),
  }),
});

Redux将在不同的状态路径中保存它,如下图所示:
将数据存储到特定状态路径,同时忽略动态参数。

我的问题是,我如何使rtk-query忽略签名参数,只是更新具有相同名称的请求的状态?

英文:

Right now, I'm using Redux Toolkit Query to fetch data from API.
But that API required a new signature in the query parameter every time we send a request. As in the code below:

export const restApi = createApi({
  reducerPath: "restApi",
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/pokemon/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query({
      query: ({ name, signature }) => `${name}?signature=${signature}`
    }),
  }),
});

Which redux will save it in a different state path as below image
将数据存储到特定状态路径,同时忽略动态参数。

My question is, how do I make rtk-query ignore the signature parameter and just update the state of the request with the same name?

答案1

得分: 2

serializeQueryArgs属性在查询端点上可用,允许根据查询参数提供“基于查询参数的自定义缓存键值”。这似乎正是您所要求的。

示例:

export const restApi = createApi({
  reducerPath: "restApi",
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/pokemon/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query({
      query: ({ name, signature }) => `${name}?signature=${signature}`,
      serializeQueryArgs: ({ queryArgs }) => {
        const { name } = queryArgs;
        return { name }; // 从缓存键中省略`signature`
      },
    }),
  }),
});
英文:

There is available on the query endpoints a serializeQueryArgs property that allows for providing "a custom cache key value based on the query arguments". This seems to be exactly what you are asking for.

Example:

export const restApi = createApi({
  reducerPath: "restApi",
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/pokemon/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query({
      query: ({ name, signature }) => `${name}?signature=${signature}`,
      serializeQueryArgs: ({ queryArgs }) => {
        const { name } = queryArgs;
        return { name }; // omit `signature` from the cache key
      },
    }),
  }),
});

huangapple
  • 本文由 发表于 2023年5月25日 01:36:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326118.html
匿名

发表评论

匿名网友

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

确定