Search code examples
reduxredux-toolkit

RTK Query — correct approach for creating endpoint data selectors


I've been playing a bit with RTK Query and I was wondering how to correctly pick data from an endpoint and returning that data filtered (or somehow updated)

I ended up making this to work

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

The in the component

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

Is this the correct approach for creating selectors in RTK Query? I'm not sure if I'm correct.

Used these links as reference 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)?


Solution

  • You should generally just use the useGetGroupAvailableAssessmentsQuery hook - you can combine that with 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) }
      }
    })