Refactor RTK Query Endpoints to use baseQuery to Remove Code Duplication

Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years 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.