How to call second redux hook after the first one completes

Viewed 28

Good day! Can't make request, i don't know how to request information

const { id } = useParams();
const { data, isLoading } = jsonApi.useFetchStrategyQuery(id);

const { currentData } = catalogApi.useGetFundQuery(data.id)

Have the above hooks and question how call the hook on line 4 after the hook on line 2 completes.

useEffect() cannot be applied

First hook:

export const jsonApi = createApi({
  reducerPath: 'jsonApi',
  baseQuery: fetchBaseQuery({ baseUrl: config.jsonUrl }),
  endpoints: build => ({
    fetchStrategy: build.query<IStrategy, string | number | undefined>({
      query: id => ({
        url: `/static/strategies/${id}.json`,
      }),
    }),
    fetchLegalEntity: build.query<LegalEntity, string>({
      query: name => ({
        url: `/static/legalEntities/${name}.json`,
      }),
    }),
  }),
});

Second hook:

export const catalogApi = createApi({
  reducerPath: 'catalogApi',
  baseQuery: fetchBaseQuery({ baseUrl: config.infoApiUrl }),
  endpoints: build => ({
    getFund: build.query<Catalog[], string | number | undefined>({
      query: id => ({
        url: `/api/Products/${id}`,
      }),
    }),
  }),
});
export const { useGetFundQuery } = catalogApi;
1 Answers

You can try and use a skipToken to skip your query when data.id doesn't have a value in it like so:

import { skipToken } from '@reduxjs/toolkit/query/react';
...
const { data, isLoading } = jsonApi.useFetchStrategyQuery(id);
const { currentData } = catalogApi.useGetFundQuery(data?.id ?? skipToken);

Above, if data?.id is undefined or null, skipToken is passed as an argument which tells redux to skip the query. Once your data has been fetched and data.id is defined, your query will re-run. You can see this part of the redux toolkit docs for more info on skips.

Related