Reputation: 646
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 AppVersion
s. 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!
Upvotes: 5
Views: 4345
Reputation: 44078
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>
)
}
Upvotes: 6