RTK Query createSelector that uses query cache

130 Views Asked by At

I'm trying to selected some data that is deeply nested within the result of the RTK Query api cache.

The issue I'm having is that I'm unsure how to define and use the custom createSelector properly so I can pass in the multiple parameters needed to get the data. I seem to run into the same error of expected 2 arguments but got 3.

From what I understand from the docs, and YouTube/articles, is that you pass in each param which will correspond with an input parameter in the selector. The final thing in the selector is the output where you grab the final data you want.

So I need to pass in 2 params. First one for the query cache signature so I can get the initial data. The second param is to filter the data in the output selector.

slice.ts

export const selectOnboardingCategoryFormInfoResult = (state: RootState, { category_id, project_id }: { category_id: number; project_id?: number }) => (!!project_id ? wordprestoApi.endpoints.getOnboardingFormInfo.select({ category_id, project_id })(state).data : undefined);
export const selectAnswer = (answer: OnboardingAnswersResponse) => answer;
export const selectApprovalByAnswer = createSelector([selectOnboardingCategoryFormInfoResult, (cats, answer: OnboardingAnswersResponse) => selectAnswer(answer)], (queryCategories, answer) => {
    if (!queryCategories) return [];

    let foundApproval: OnboardingApproval | undefined = undefined;
    if (!queryCategories) return foundApproval;

    for (const category of queryCategories) {
        const questionResult = category.OnboardingQuestions.find(question => question.OnboardingAnswers.length > 0 && question.OnboardingAnswers[0].id === answer?.id);

        if (questionResult) {
            foundApproval = questionResult.OnboardingAnswers[0].OnboardingAnswerApprovals[0];
            break;
        }
    }

    return foundApproval;
});

usage

const storedApproval = useSelector(state => selectApprovalByAnswer(state, { project_id: answer?.project_id, category_id }, answer));

I'm sure I'm missing a key piece of understanding here. Any help would be fantastic :)

0

There are 0 best solutions below