Reat Native & RTK Query - 请求成功时调用其他终结点



我是Redux&RTK查询,我不明白当另一个端点的响应成功时,如何从另一个终结点获取数据。

我创建了一个类似的API:

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: () => ({}),
})

我为每个资源都有一个模块,例如:

// /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}` })
})
}

因此,在我的组件中,我称之为:

const { data: matches, error, isLoading } = useFetchMatchesQuery('explorer')

现在,当useFetchMatchesQuery成功时,我需要做的是:

  1. useFetchMatchesQuery响应数据创建一个具有所有匹配id的数组
  2. 调用其他查询以获取参数中具有matchsIds的其他数据
  3. 在渲染matches数据的同一组件中使用响应

这里的主要选项是在同一组件中有第二个useSomeOtherQuery()钩子,但"跳过";直到第一个查询完成。这可以通过传递{skip: false}作为选项,也可以传递skipToken变量作为查询参数来实现:

https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching

这是我使用的解决方案:

// /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])

最新更新