reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.65k stars 1.16k forks source link

How to make RTK Query createApi's mutation throw rejection? #2555

Closed zivgit closed 2 years ago

zivgit commented 2 years ago

The current code execution will enter then, How to get here.

getList({ id }).catch(() => {
    // How to get here
});

baseQuery.js


import { fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react';

const baseQueryWithRetry = retry( fetchBaseQuery({ baseUrl: process.env.REACT_APP_BASE_URL, }), { maxRetries: 6 } );

export const baseQueryWithReauth = async (args, api, extraOptions) => { try { const result = await baseQueryWithRetry(args, api, extraOptions) as { data: { RES: string } }; if (result.data.RES) { const { body } = JSON.parse(result.data.RES); switch (body.code) { case '000000': return { ...result, data: body } default: debugger throw new Error('body.message'); } } return result; } catch (err: any) { debugger return Promise.reject(err); } }

>services.js

import { createApi } from '@reduxjs/toolkit/query/react'; import { baseQueryWithReauth } from './baseQuery';

export const quoteApi = createApi({ reducerPath: 'quoteApi', baseQuery: baseQueryWithReauth, endpoints: (builder) => ({ getList: builder.mutation<any, object>({ query: (body) => ({ url: 'getPriceList', method: 'POST', body, }), }), }), refetchOnReconnect: true, });

phryneas commented 2 years ago

Copying my answer from StackOverflow:

This is so that your application is not littered with uncaught async exceptions if you are not interested in the result.

You can unwrap the result to get to "throwing" behaviour:

getList({ id }).unwrap().catch(() => { How to get here });

That said, it is very likely that getList should be a query, not a mutation. Mutations are things that change data on your server.

zivgit commented 2 years ago

This method is very effective, thank you