I'm currently integrating RTK and RTKQ into an existing project and want to make sure that the code I'm writing follows best practices. From the RTK Query documentation, it seems there is no functional difference between the two approaches, and both are used.
Initially I was using the hook naming scheme to export the individual hooks directly from the Api object (useGetDataQuery, etc). However, from what I can tell, using the actual endpoints and then using useQuery(), useLazyQuery(), etc... on them is a better approach since you spend significantly less time rewriting exports and imports if you happen to change the name of the endpoint or what kind of query you want to use it with. The only thing I've seen so far is that the specifically named endpoint hooks seem to play better with my IDE (WebStorm).
I've been using the endpoints like so:
const splitApi = emptyApi.injectEndpoints({...});
export const {
getData
} = splitApi.endpoints;
// In a separate file
import { getData } from 'splitApi';
const dataQuery = getData.useQuery();
Is there a benefit to using the "use<endpoint><modifier> approach over the "<endpoints>.<endpoint>.<modifier>" approach? Is there anything wrong with the approach I've described above?
CodePudding user response:
api.useGetPokemonQuery
and api.endpoints.getPokemon.useQuery
are literally the exact same function. However, we assume that most people are typically interested in calling the "query" and "mutation" hooks, so those are the ones made accessible on the api
object itself and given matching distinct names.
Either works, but I'd typically default to re-exporting the ones off the API object personally. I wouldn't expect "renaming endpoints" to be happening very often.
Note that if you're doing api.injectEndpoints()
, the return value is the same api
object, but with updated TS types. So, from within this file, you could then do export const { useGetDataQuery } = splitApi
.