Gleb_Sh
Gleb_Sh

Reputation: 41

Redux toolkit query. useLazyQuery

Try to understand how to structure queries. What I have now:

File for CRUD:

export const PromoService = apiClient.injectEndpoints({
    endpoints: (build) => ({
        fetchPromoById: build.query<
            Promotion,
            { ppeType: PpeType; id: string }
        >({
            query: ({ ppeType, id }) => apiQuery(ppeType, 'fetchPromoById', id),
            providesTags: (_result, _err) => [{ type: 'Promo' }],
        }),

        fetchPromoByCategory: build.mutation<
            PromotionData,
            { ppeType: PpeType; type: string; bannerId: string }
        >({
            query: ({ ppeType, type, bannerId }) => ({
                url: apiQuery(ppeType, 'fetchPromoByCategory'),
                method: 'POST',
                body: fetchPromoByCategoryBody(type, bannerId),
            }),
            invalidatesTags: ['Promo'],
        }),
    }),
});

export const { useLazyFetchPromoByIdQuery, useFetchPromoByCategoryMutation } =
    PromoService;

File for slices:

const initialState: PromotionState = {
    chosenPromotion: {} as Promotion,
    promoList: [],
};

const promoSlice = createSlice({
    name: 'promo',
    initialState,
    reducers: {
        setChosenPromotion: (state, action: PayloadAction<Promotion>) => {
            state.chosenPromotion = action.payload;
        },
        setPromoList: (state, action: PayloadAction<Promotion[]>) => {
            state.promoList = action.payload;
        },
    },
});

Component:

const [fetchPromoByCategory, { isLoading, data: categoryData }] =
    useFetchPromoByCategoryMutation({
        fixedCacheKey: 'shared-update-promo',
    });

const [trigger, result] = useLazyFetchPromoByIdQuery();
const chosenPromo = result.data;

useEffect(() => {
    chosenPromo && dispatch(setChosenPromotion(chosenPromo));
}, [chosenPromo]);

There is no problem get data from useMutation in different components skipping the stage of store data via reducer. Just use fixedCacheKey and it works fine.

Is it possible to use similar approach for getting data in different components with useLazyQuery? I use additional dispatch to store data from useLazyQuery but I'm sure it's not appropriate approach.

Upvotes: 0

Views: 2843

Answers (1)

phry
phry

Reputation: 44276

It is perfectly valid to have multiple different query cache entries at once, so useLazyQuery will not initialize to one of them - it will get it's arguments once you call the trigger function.

It looks like you should use useQuery here, sometimes with the skip parameter when you don't want anything fetched from the start.

Upvotes: 0

Related Questions