redux RTK查询-创建端点数据选择器的正确方法

ndh0cuux  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(129)

我一直在玩RTK查询,我想知道如何正确地从端点中选取数据,并返回经过过滤(或以某种方式更新)的数据
最后我把这个做成了工作

export const selectGroupAvailableAssessments = (cacheKey) => {
  return rtkQueryApi.endpoints.getGroupAvailableAssessments.select(cacheKey);
};
// returns object with status, endpointName, data, error, isLoading, etc

export const selectGroupAvailableAssessmentsByAssessmentId = (cacheKey, assessmentId) => createSelector(
  selectGroupAvailableAssessments(cacheKey),
  (availableAssessments) => {
    if (!availableAssessments.data) return null;
    const { data } = availableAssessments;

    return data.find((item) => item.id === assessmentId);
  },
);
// returns the selector "data" assessments filtered by id

元件中的

const assessmentById = useSelector(selectGroupAvailableAssessmentsByAssessmentId(cacheKey, assessmentId));

这是在RTK查询中创建选择器的正确方法吗?我不确定我是否正确。
使用这些链接作为参考How to use RTK query selector with an argument?
https://medium.com/nmc-techblog/rtk-query-best-practices-e0296d1679e6
How to call endpoint.select() in RTK query with an argument to retrieve cached data (within another selector)?

e5nszbig

e5nszbig1#

通常只使用useGetGroupAvailableAssessmentsQuery钩子-可以将其与selectFromResult结合使用。

const selectFiltered = createSelector(
  result => result.data,
  (_, assessmentId) => assessmentId,
  (data, assessmentId) => {
     return data.find((item) => item.id === assessmentId);
  }
)

const result = useGetGroupAvailableAssessmentsQuery(something, {
  selectFromResult(result) {
    return { ...result, data: selectFiltered(result, assessmentId) }
  }
})

相关问题