redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

Typescript error when wrapping createApi

Open IdanGoor opened this issue 3 years ago • 0 comments

Hi everyone. I have multiple apps which need to use the same API of RTK-Query, but each one of them has to pass a different baseQuery function because of different headers and custom fetch function. Therefore, I created a function called createBaseApi which accepts a baseQuery and supposes to build the api with all the injected endpoints. Unfortunately, I'm struggling with managing the types correctly.

I created a simple example to demonstrate the current issue. As you can see, there is a type error when I try to preform optimistic update in userApi: Screen Shot 2022-09-30 at 16 22 20

These are the main API files:

// baseApi.ts

const createBaseApi = (
  baseQuery: BaseQueryFn<FetchArgs, any, FetchBaseQueryError>
) => {
  const baseApi = createApi({
    reducerPath: "baseApi",
    baseQuery,
    tagTypes: [],
    endpoints: () => ({}),
  })

  return injectUserApi(baseApi)
}
// userApi.ts

interface User {
  id: string
  name: string
}

interface GetUserArgs {
  id: User["id"]
}

interface UpdateUserArgs {
  id: User["id"]
  name: User["name"]
}

const injectUserApi = <E extends EndpointDefinitions>(
  api: Api<
    BaseQueryFn<FetchArgs, any, FetchBaseQueryError>,
    E,
    string,
    string,
    ModuleName
  >
) => {
  const userApi = api.injectEndpoints({
    endpoints: builder => ({
      getUser: builder.query<User, GetUserArgs>({
        query: ({ id }) => ({
          url: `/users/${id}`,
          method: "GET",
        }),
        providesTags: (_, __, { id }) => [{ type: "User", id }],
      }),
      updateUser: builder.mutation<User, UpdateUserArgs>({
        query: ({ id, name }) => ({
          url: `/users/${id}`,
          method: "PUT",
          body: { name },
        }),
        async onQueryStarted({ id, name }, { dispatch, queryFulfilled }) {
          const patchResult = dispatch(
            userApi.util.updateQueryData("getUser", { id }, draft =>
              Object.assign(draft, { name })
            )
          )
          queryFulfilled.catch(patchResult.undo)
        },
      }),
    }),
  })
}

Does anyone know how should I fix the typing? Or better yet - is there a simpler way to initialize the createApi to fit this use-case?

Thanks

IdanGoor avatar Sep 30 '22 13:09 IdanGoor