react-apollo-hooks icon indicating copy to clipboard operation
react-apollo-hooks copied to clipboard

Is it possible to map the result of one query to another query?

Open RyanPayso13 opened this issue 5 years ago • 1 comments

I have an initial usePaginatedQuery which gives me an array of ids:

  const {
    resolvedData: policies,
    isLoading,
    isError,
  } = usePaginatedQuery(
    [`policies`],
    () => {
      return axios.get(`/v1/policies?page=${page}`);
    },
    {
      enabled: isEnabled,
      retry: false,
    }
  );

I need to iterate over the id in the resolved data array to subsequently fetch data associated with that id:

usePaginatedQuery(
    [`policy.${id}.documents`],
    () => {
      return axios.get(
        `/v1/policies/${id}/documents?page=${page}`
      );
    },
    {
      enabled: isEnabled,
      retry: false,
    }
  );

I then need an array of documents that are associated with the appropriate id to build my react-table e.g.

[{id: '123', documents: ['foo.txt', 'bar.txt']}, {id: '456', documents: ['xxx.txt', 'yyy.txt']}]

Is there a way to do this in react-query?

I looked at documentation for dependant queries but it is not quite what i need.

RyanPayso13 avatar Nov 23 '20 10:11 RyanPayso13

I actually managed to get what i wanted by constructing a new query like so:

  const { data: policyDocuments } = useQuery(
    ['policy.documents'],
    async () => {
      const requests = policies?.data.content.map((policy: Policy): any => {
        return axios.get(`/v1/policies/${policy.policyReference}/documents`);
      });

      const data = await Promise.allSettled(requests);
      const result = (data as any).flatMap(
        (d: Record<string, any>, i: number) => {
          const referenceIndex = i;

          return d.value.data.content.map(
            (v: string): Record<string, string | number> => {
              return {
                policyReference: policyReferences[referenceIndex],
                document: v,
              };
            }
          );
        }
      );

      return result;
    },
    {
      enabled: policies,
      retry: false,
    }
  );

If there is a better way to do this with react-query please let me know 👍

RyanPayso13 avatar Nov 23 '20 11:11 RyanPayso13