0

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)?

1 Answer 1

0

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) }
  }
})
Sign up to request clarification or add additional context in comments.

6 Comments

I want to avoid reusing the original useGetGroupAvailableAssessmentsQuery that why I thought about just getting the data with a selector. I've also got adviced to use createEntityAdapter since I just want to get the assessments entity by its id :).
Why do you want to avoid it? Those selectors are really meant to be used when you are not in a React component - if you are in a component, you really should use the hooks.
The hook is a bit verbose due to the options object that I'm using and I was wondering if using a selector was a better approach. However your solution will work well depending the case. Thank you for the effort mantining the project! I love having several options.
You could have a global variable with the full options object if that helps you abstract it better? :)
Works like a charm by the way!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.