'ReferenceError: Cannot access 'rootReducer' before initialization

I am using reduxjs toolkit, redux-persist and ducks architecture. So, I created store. Wrapped my App component into Provider and PersistGate, then I got this error: ReferenceError: Cannot access 'rootReducer' before initialization

store.ts:

import {persistReducer, persistStore} from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import {rootReducer} from './ducks';
import {configureStore} from '@reduxjs/toolkit';
import createThunkErrorHandlerMiddleware from 'redux-thunk-error-handler';
import {ThunkErrorsHandler} from './middlwares/catchThunkErrors';
import {authMiddleware} from './middlwares/authMiddlware';

const persistConfig = {
  key: 'root',
  storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const errorHandlerMiddleware = createThunkErrorHandlerMiddleware({
  onError: ThunkErrorsHandler,
});

export const store = configureStore({
  reducer: persistedReducer,
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware({
      serializableCheck: false,
    }).concat(authMiddleware, errorHandlerMiddleware),
});

export const persistor = persistStore(store);
export type rootState = ReturnType<typeof store.getState>;

ducks.ts:

import {combineReducers} from 'redux';
import * as auth from './auth';

export const rootReducer = combineReducers({
  auth: auth.reducer,
});

export const actions = {
  auth: auth.actions,
};

export const selectors = {
  auth: auth.selectors,
};

Error occures on line 11 of my createAsyncThunk function:

import {createAsyncThunk} from '@reduxjs/toolkit';
import {API_URL, SIGN_UP_URL} from '../../constants';
import {IAuthData} from './types';
import {http} from '../../services/http';

export const SignUp = createAsyncThunk(
  `${API_URL}/auth/sign_up`,
  async (authData: IAuthData) => {
    const {data} = await http.post(SIGN_UP_URL, authData);
    return data;
  }, // error here
);

repo link: https://gitlab.com/Banan4ikk/accelerant

Can you help. what can be cause of error.



Solution 1:[1]

Problem was in my http class

import axios, {AxiosError, AxiosInstance} from 'axios';
import {store} from '../redux/store';
import {actions} from '../redux/ducks';
import {API_URL} from '../constants';

export class Http {
  constructor(private readonly _axios: AxiosInstance) {
    this.useInterceptors();
  }

  setAuthorizationHeader(token: string): void {
    this._axios.defaults.headers.common.Authorization = `Bearer ${token}`;
  }

  unsetAuthorizationHeader(): void {
    delete this._axios.defaults.headers.common.Authorization;
  }

  private useInterceptors(): void {
    this._axios.interceptors.response.use(
      undefined,
      (error: AxiosError): Promise<AxiosError> => {
        if (error.response?.status === 401) {
          store.dispatch(actions.auth.signOut());
        }
        return Promise.reject(error.response?.data);
      },
    );
  }

  get get() {
    return this._axios.get;
  }

  get post() {
    return this._axios.post;
  }

  get put() {
    return this._axios.put;
  }

  get patch() {
    return this._axios.patch;
  }
  get delete() {
    return this._axios.delete;
  }

  get request() {
    return this._axios.request;
  }

  get axios(): AxiosInstance {
    return this._axios;
  }
}

export const http = new Http(
  axios.create({
    baseURL: API_URL,
    timeout: 60000,
  }),
);

I caught circular dependency, when I was calling store.dispatch(), after I removed it, the error is gone.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xantin