【问题标题】:Reat Native & RTK Query - Call an other endpoint when request is successReact Native & RTK Query - 请求成功时调用另一个端点
【发布时间】:2022-01-15 20:35:05
【问题描述】:

我是 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 数据的同一组件中使用响应。

谢谢你的帮助????

【问题讨论】:

    标签: javascript react-native redux rtk-query


    【解决方案1】:

    这是我使用的解决方案:

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

    【讨论】:

    • 谢谢@markerikson :)
    【解决方案2】:

    这里的主要选项是在同一组件中添加第二个useSomeOtherQuery() 挂钩,但“跳过”该查询直到第一个查询完成。这可以通过将{skip: false} 作为选项传递,或者将skipToken 变量作为查询参数传递:

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

    【讨论】:

    • 我要试试这个解决方案,谢谢你的回复:)
    猜你喜欢
    • 2022-01-17
    • 2022-10-05
    • 2022-08-22
    • 1970-01-01
    • 2017-08-28
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    相关资源
    最近更新 更多