Home > Net >  What does enhanceEndpoints() do in Redux Toolkit Query?
What does enhanceEndpoints() do in Redux Toolkit Query?

Time:06-26

According to the official Redux Toolkit Query documentation here for enhanceEndpoints():

Unlike injectEndpoints, the partial endpoint definitions will not replace existing definitions, but are rather merged together on a per-definition basis (ie, Object.assign(existingEndpoint, newPartialEndpoint)).

Can't we already do this with the following?

api.injectEndpoints({ overrideExisting: false, endpoints:...})

So why do we need an additional API?

Also, I noticed the example given there:

import { api } from './api'
const enhancedApi = api.enhanceEndpoints({
  addTagTypes: ['User'],
  endpoints: {
    getUserByUserId: {
      providesTags: ['User'],
    },
    patchUserByUserId: {
      invalidatesTags: ['User'],
    },
    // alternatively, define a function which is called with the endpoint definition as an argument
    getUsers(endpoint) {
      endpoint.providesTags = ['User']
      endpoint.keepUnusedDataFor = 120
    },
  },
})

...does not use

...(builder)=>...builder.query(...)...

Is this some sort of an alternative syntax?

CodePudding user response:

overrideExisting: false of injectEndpoints means that if the endpoint already exists, you get an error message and nothing happens to the endpoint. If true, it will replace your existing endpoint.

=> injectEndpoints can add or replace endpoints with completely new code, but it cannot modify an endpoint definition.

enhanceEndpoints on the other hand cannot create a new endpoint definition - but it allows you to modify an existing one.

It has two notations:

  • either you specify a partial endpoint definition as an object. That object will just be merged with the endpoint definition
  • or you have a callback function. That will allow you to access the old endpoint definition, maybe read it and also write to it.

Either way: if that endpoint did not exist before, nothing will happen.

  • Related