Refactor RTK Query Endpoints to use baseQuery to Remove Code Duplication

Share this video with your friends

Social Share Links

Send Tweet
Published a year ago
Updated a year ago

We can reduce code duplication using a baseQuery from RTK Query. We do this by moving duplicate code into a baseQuery function and writing query functions instead of queryFn. The return value of those query functions will be passed on as first argument into the baseQuery.

Instructor: [0:00] If we look at our code, we still have a lot of duplicate code here, between this query function, and this other query function. We can reduce that, and that's where base query comes into play. [0:12] Let's just take off this code and move it into our base query. Of course, calling this for every endpoint wouldn't be perfect because we don't always want to call this one URL. Let's say, we want to pass in a variable here and we get it as the argument to base query.

[0:32] Now, we can remove our query function here. I'll quickly copy this URL and instead, add a function named query that returns this URL. We can do the same down here. We add a function named query, which gets a name as an argument as before, and we return this URL.

[0:59] Like that, we removed a lot of code duplication.

egghead
egghead
~ 48 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today