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

1

9

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!

Hilariohilarious answered 6/7, 2021 at 17:25 Comment(0)
B
2

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.

Borsch answered 6/7, 2021 at 19:32 Comment(2)
But is there at least any approach to fetch an array of results? In my case, it's required to have all results in place to display smth on the screen and the arguments array is coming from the memorized selectorProspect
Not at the moment, no.Borsch

© 2022 - 2024 — McMap. All rights reserved.