Can I write a queryFn that conditionally calls the baseQuery? #3532
-
This is a very basic setup of what I'm trying to do: // api.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const myApi = createApi({
reducerPath: 'myApi',
baseQuery: fetchBaseQuery({
baseUrl: '/api/v1/'
}),
endpoints: (builder) => ({
getUser: builder.query({
// This is the basic query that always gets called
query: (userId) => `users/${userId}`,
// But I just want to return an empty object if `userId` is null
queryFn: (arg) => {
if (!arg) {
return { data: {} }
} else {
// How do I call the regular query here?
}
}
})
})
})
export const { useGetUserQuery } = myApi That way, inside of my component, I can just do something like this: // UserName.jsx
export default function UserName (props) {
const { data } = useGetUserQuery(props.userId)
// The query succeeds even if the userId is null, it just displays "Anonymous"
return (
<span>{data?.name || 'Anonymous'}</span>
)
} Is there a way I can do this, so I don't need to write a "skip" check in every invocation of |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
yes, the fourth parameter passed to queryFn is |
Beta Was this translation helpful? Give feedback.
-
Thanks. I thought the documentation was confusing, but it seemed to do the trick. The final implementation looks like this: export const myApi = createApi({
reducerPath: 'myApi',
baseQuery: fetchBaseQuery({
baseUrl: '/api/v1/'
}),
endpoints: (builder) => ({
getUser: builder.query({
queryFn: (userId, _api, _extraOptions, baseQuery) => {
if (!userId) {
return { data: {} }
} else {
return baseQuery(`users/${userId}`)
}
}
})
})
}) |
Beta Was this translation helpful? Give feedback.
yes, the fourth parameter passed to queryFn is
fetchWithBaseQuery
, allowing you to get the result of calling the base query with a given parameterhttps://redux-toolkit.js.org/rtk-query/usage/customizing-queries#performing-multiple-requests-with-a-single-query
https://redux-toolkit.js.org/rtk-query/api/createApi#queryfn