V
V
Viktor Putin2021-11-11 03:34:12
typescript
Viktor Putin, 2021-11-11 03:34:12

What's the difference in axios import in createAsyncThunk?

Greetings! Can you please tell me what is the difference between using axios createAsyncThunkthrough direct import of an object from create-api.tsor through an extra argument thunkApi.extra?

create-api.ts

export const createAPI = (onUnauthorized: UnauthorizedCallback): AxiosInstance => {
  const axiosConfig = axios.create({
    baseURL: BACKEND_URL,
    timeout: REQUEST_TIMEOUT,
  });

  axiosConfig.interceptors.request.use((config: AxiosRequestConfig) => {
    const token = getAuthToken();

    if (token) {
      config.headers['x-token'] = token;
    }

    return config;
  });

  axiosConfig.interceptors.response.use(
    (response: AxiosResponse) => response,
    (error: AxiosError) => {
      const { response } = error;

      if (response?.status === HttpCode.Unauthorized) {
        return onUnauthorized();
      }

      return Promise.reject(error);
    },
  );


store.ts

const store = configureStore({
  reducer: rootReducer,
  devTools: true,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      thunk: {
        extraArgument: { api },
      },
    }).concat(redirect),
});


movie.slice.ts

export const getAllMovies = createAsyncThunk<
  Movie[],
  void,
  {
    extra: { api: AxiosInstance };
  }
>('movie/getAllMovies', async (_, thunkApi) => {
  const api = thunkApi.extra.api;
  const { data } = await api.get<ApiMovieData[]>(AppRoutes.Movies);
  const adaptedData = data.map((movie) => adaptMovieDataToClient(movie));

  return adaptedData;
});



If you import an object apifrom create-api.tsand make a request through it, you must additionally call the y method in the .unwrap()component dispatch. If you import axiosvia thunkApi.extra, then you need to additionally specify the types of y createAsyncThunkand create a variable. I can not understand how to do it better, and whether there is a difference in approaches.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question