Soy nuevo en Redux y RTK Query y no entiendo cómo puedo obtener datos de otro punto final cuando la respuesta de otro punto final es exitosa.
Creé una API como esa:
import { Config } from '@/Config' import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' const baseQuery = fetchBaseQuery({ baseUrl: Config.API_URL }) const baseQueryWithInterceptor = async (args, api, extraOptions) => { let result = await baseQuery(args, api, extraOptions) if (result.error && result.error.status === 401) { // Deal with unauthorised } return result } export const api = createApi({ baseQuery: baseQueryWithInterceptor, endpoints: () => ({}), })Tengo módulos para cada recurso, ejemplo:
// /modules/matches import { api } from '../../api' import { fetchMatches } from '@/Services/modules/matches/fetchMatches' export const matchApi = api.injectEndpoints({ endpoints: build => ({ fetchMatches: fetchMatches(build), }), overrideExisting: false, }) export const { useFetchMatchesQuery } = matchApi // /modules/matches/fetchMatches export const fetchMatches = build => { return build.query({ query: type => ({ url: `matches/${type}` }) }) }Entonces, en mi componente lo estoy llamando con:
const { data: matches, error, isLoading } = useFetchMatchesQuery('explorer') Ahora, lo que debo hacer cuando useFetchMatchesQuery tiene éxito es:
useFetchMatchesQuerymatchsIds en paramsmatches .La opción principal aquí es tener un segundo gancho useSomeOtherQuery() en el mismo componente, pero "omitir" esa consulta hasta que se complete la primera consulta. Esto se puede hacer pasando {skip: false} como una opción, o la variable skipToken como argumento de consulta:
https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching
Aquí está la solución que usé:
// /Containers/MyContainer const [matchesIds, setMatchesIds] = useState([]) const { data: matches, error: matchesError, isLoading: matchesIsLoading, } = useFetchMatchesQuery('explorer') const { data: winnerMarkets, error: winnerMarketsError, isLoading: winnerMarketsIsLoading, } = useFetchWinnerMarketsQuery(matchesIds, { skip: matchesIds.length === 0 }) useEffect(() => { if (matches) { const mIds = [] matches.map(match => { mIds.push(match.id) }) setMatchesIds(mIds) } }, [matches])