Redux ToolKit Query - Make multiple queries in the same component dependant on each other
Asked Answered
E

1

5

I'm trying to use RTK Query in a NextJS app to fetch multiple entities from an API. I have the App and AppVersion models. When the component loads I need to fetch the App and then fetch the appropriate AppVersions. An App has the currentVersionId property that links to and AppVersion.

The code fails because the component is rendered without the router at first, it can't get an app and there's no app.currentversionId.

I have two slices that fetch the appropriate objects from a RESTful API.

function AppsShow() {
  const router = useRouter()
  const { id } = router.query
  const { data: app } = useGetAppQuery(parseInt(id, 10)) // from RTK Query slice
  const currentVersion = useGetVersionQuery(app?.currentVersionId) // from RTK Query slice

  return (
    <div></div>
  )
}

What is the appropriate pattern to use here? Thank you!

Eurus answered 15/6, 2021 at 19:34 Comment(0)
J
6

Use the skip option :)

function AppsShow() {
  const router = useRouter()
  const { id } = router.query
  const { data: app } = useGetAppQuery(parseInt(id, 10)) // from RTK Query slice
  const currentVersion = useGetVersionQuery(app?.currentVersionId, { skip: !app?.currentVersionId })

  return (
    <div></div>
  )
}

Alternatively you could use the skipToken that is also exported by RTK-Query (this approach might play better with TypeScript)

function AppsShow() {
  const router = useRouter()
  const { id } = router.query
  const { data: app } = useGetAppQuery(parseInt(id, 10)) // from RTK Query slice
  const currentVersion = useGetVersionQuery(app?.currentVersionId ?? skipToken)

  return (
    <div></div>
  )
}
Jasminejason answered 15/6, 2021 at 20:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.