Search code examples
reduxredux-toolkitrtk-query

RTK Query: How to query an array of IDs and return an array of retrieved data?


I am working with "Redux Toolkit Query" and run into the situation where I have an array of place ids and want to return an array of retrieved places. However, with my current setup, I am only able to query a single place, but not the entire compiled list of places.

Hooks where i call the query:

function ShowPlaceList() {
  const placeIDs = [1, 2, 3, 4, 5];

  const { data, isFetching, isLoading } = useGetPlaceByIdQuery({
    placeID: placeIDs,
  });

  // data should be an array 
  return (
    <div>
      {data.map(function (item, i) {
        return <ShowPlace {...item} />;
      })}
    </div>
  );
} 

Simplified Slice:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'


export const placeApi = createApi({
  reducerPath: 'placeApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://providePlace.co/api/v2/' }),
  endpoints: (builder) => ({
    getGetPlaceById: builder.query({
      query: ({placeID}) => `place/${placeID}`,
    }),
  }),
})


export const { useGetPlaceByIdQuery } = placeApi

I am happy for any hint!


Solution

  • Since you are bound to the rules of hooks and cannot call hooks in a loop, the most natural way of doing this would be to call useGetPlaceByIdQuery within ShowPlace, not the parent component.