English 中文(简体)
难道我们能提供RTK Query中APIC失败的缺省数据吗?
原标题:Is there a way we can provide default data on API fail in RTK Query?

I am trying RTK Query for the first time to fetch some data in a react + ts application. Is there a way where I could specify some default data if the API fails? What is the good practice that should be followed here?

export const dummyApi = createApi({
  reducerPath:  dummyApi ,
  baseQuery,
  tagTypes: [ Dummy ],
  endpoints: (builder) => ({
    getDummy: builder.query<DummyItem[], void>({
      query: () => `/dummy`,
      providesTags: [ Dummy ],
      transformResponse: (response: DummyApiResponse) =>
        return [...someDefaultListOfItems, ...response.data];
      },
    }),
  }),
});

我在<代码>transformErrorResponse中尝试过一些东西,但可以查到。

问题回答
const handleError = (args, { queryFulfilled }) => {
  try {
    const { data } = await queryFulfilled;
  } catch (error) {
    // return default data in here
  }
};
export const dummyApi = createApi({
  reducerPath:  dummyApi ,
  baseQuery,
  tagTypes: [ Dummy ],
  endpoints: (builder) => ({
    getDummy: builder.query<DummyItem[], void>({
      query: () => `/dummy`,
      providesTags: [ Dummy ],
      transformResponse: (response: DummyApiResponse) =>
        return [...someDefaultListOfItems, ...response.data];
      },
      onQueryStarted: handleError
    }),
  }),
});

You can try onQueryStarted API and handle error by using try catch block as my example. Hope it s helfull.





相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签