question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Type safety in RTK query endpoints

See original GitHub issue

I am trying to decouple the data access layer from the rest of my app (sort of a clean code good practice).

For that I implemented the following baseQuery:

export interface DataResponseError {
    data?: never;
    error: 'string';
}

export interface DataResponseSuccess<T> extends DataResponseCommon {
    data: T;
    error?: never;
}

export type DataResponse<T = any> = DataResponseError | DataResponseSuccess<T>;

type DataAccessMethod = (payload?: any) => Promise<DataResponse<any>>;

const queryService: BaseQueryFn<DataAccessMethod, unknown, unknown> = async (dataAccessMethod, api) => {
    const { error, data } = await dataAccessMethod();

    if (error) {
        return { error };
    }

    return { data };
};

Then I will define an service interface, for example:

export interface ExampleService {
    getNumber: () => Promise<DataResponse<number>>;
}

And then implement that interface:

export const exampleService: ExampleService = {
    getNumber: async () => {
        const response = await axios.get<number>("/number");

        return response;
    },
};

Finally create the hooks using the RTK utility:

export const extendedApiSlice = serviceSlice.injectEndpoints({
    endpoints: (builder) => ({
        getNumber: builder.query<number, void>({
                query: () => exampleService.getNumber,
            }),
    }),
});

In this case everything works as expected. But what would happen if I change the return value of the getNumber endpoint from RTK, say:

export const extendedApiSlice = serviceSlice.injectEndpoints({
    endpoints: (builder) => ({
        getNumber: builder.query<**string**, void>({
                query: () => exampleService.getNumber,
            }),
    }),
});

Typescript doesn’t alert me that exampleService.getNumber returns a number and that that is incompatible with what the RTK endpoint definition (<string, void>) expects.

I am a little bit lost on what class|type|module in RTK should I overwrite to achieve this kind of type safety.

Thanks in advance!

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
phryneascommented, May 30, 2022

As for the toast, just using the listenerMiddleware to listen for the rejected action might be the better choice.

0reactions
markeriksoncommented, Jun 29, 2022

Closing as I think this has been reasonably answered.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Usage With TypeScript - Redux Toolkit
RTK Query provides a skipToken export which can be used as an alternative to the skip option in order to skip queries, while...
Read more >
Redux Essentials, Part 8: RTK Query Advanced Patterns
RTK Query allows multiple components to subscribe to the same data, and will ensure that each unique set of data is only fetched...
Read more >
createApi - Redux Toolkit
createApi is the core of RTK Query's functionality. It allows you to define a set of "endpoints" that describe how to retrieve data...
Read more >
Server Side Rendering - Redux Toolkit
Pre-fetch all queries via the initiate actions, e.g. store.dispatch(api.endpoints.getPokemonByName.initiate(name)); Wait for each query to ...
Read more >
Queries - Redux Toolkit
This is the most common use case for RTK Query. A query operation can be performed with any data fetching library of your...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found