François Richard
François Richard

Reputation: 7045

Reduxtoolkit createApi how to mix and parse two endpoints results?

tldr; How to mix two or more createApi endpoints results ?

So I'm using createApi from reduxToolkit and the problem I have quite simple but I'm kinda lost in this huge documentation of this beautiful tool.

The idea is that I have a view that will mix data coming from two different api endpoints , for example:

/users /cars

That view will display an array mixing both results (for example the cars images are only in /cars).

A little bit like transformResponse but for 2 endpoints

What is the right way to do this mixing ? (doing that in the view doesn't seems the best and I don't want to that backend neither).

You may tell me use a reducer, but where a reducer/slice takes places in the createApi pattern ? that's what I don't get.

Upvotes: 1

Views: 1213

Answers (1)

traianus
traianus

Reputation: 111

You can combine the result outside of rtk query.

    const {data: data1} = useAQuery(...);
    const {data: data2} = useBQuery(...);
    const combined = useMemo(() => {...combine data1, data2}, [data1, data2]);

If it's needed in multiple components, you can create a custom hook useCarsAndUsers(...) to avoid code duplication.

Upvotes: 1

Related Questions