0

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.

François Richard
  • 6,817
  • 10
  • 43
  • 78

1 Answers1

1

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.

traianus
  • 111
  • 1
  • 7
  • yes that's a good advice to do this clean in the views, but is there any clean to directly do this on the rtk/store side ? that's my question :p – François Richard Oct 22 '21 at 13:13
  • Only if you make it one endpoint, by using something like `queryFn`. But then you won't be able to use them individually any more. – phry Oct 23 '21 at 08:22
  • Agree with @phry. It's probably not a good practice to do it in rtk. – traianus Oct 26 '21 at 09:44