英文:
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}`
}),
}),
});
我的问题是,我如何使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
},
}),
}),
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论