Search code examples
reactjsrtk-query

send multiple RTK query request in response of another RTK Query


I am new to RTK Query and when I fetch some data from an endpoint I get a response of an array of objects for each id of item in the list I have to call another API to get the details of each item. but I do not know have to achieve this.

for example:

query: () => '/posts'; // response is ==> [{id: 21, title:'Hello world'}] 

and the for the details of the post with an id of 21

query: (id) => `post/${id}/detail`; // response { description:'', img:'', ... }

I need to show all posts with details. and for that, I have to get all the details on the list first and then return the result from query to later show it on the page.


Solution

  • i came up with this so far

    
    import { createApi } from '@reduxjs/toolkit/query/react';
    import axiosBaseQuery from 'api/axiosBaseQuery';
    import axios from 'services/request';
    
    export const postsApi = createApi({
        reducerPath: 'api/portfolio',
        baseQuery: axiosBaseQuery(),
        endpoints: (builder) => ({
            getUserPosts: builder.query({
                async queryFn() {
                    // get a random user
                    const postsList = await axios.get('/posts');
                    if (postsList.error) return { error: postsList.error };
                    // const result = await axios.get(`/market/instruments/${item.refId}/summary`);
                    const endpoints = postsList.data.map((item) =>
                        axios.get(`/post/${item.id}/details`)
                    );
                    let error = null;
                    let data = null;
                    try {
                        data = await Promise.all(endpoints).then((res) => {
                            return res.map((item, index) => {
                                return { ...item.data, ...postsList.data[index] };
                            });
                        });
                    } catch (err) {
                        error = err;
                    }
    
                    return data ? { data } : { error };
                }
            })
        })
    });
    
    export const { useGetUserPostsQuery } = postsApi;