How do I resolve this ReferenceError: Cannot access ‘authSlice’ before initialization?

I have a problem using React together with Redux, the problem is this:

I’m getting an error:

ReferenceError: Cannot access ‘authSlice’ before initialization

I think the problem is that I have a class called http, and there I import store, and then in my slice class I import an http method, I think that’s it. But it’s because I need to access the store, I attach my store, segment and http class:

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { HOST } from "../http/utils";
import makeApiCall from "../http"; //Possible cause

const accessToken = localStorage.getItem("accessToken");
const refreshToken = localStorage.getItem("refreshToken");
const username = localStorage.getItem("username");

const initialState = {
  username: username || null,
  password: null,
  isLoading: false,
  error: null,
  accessToken: accessToken || null,
  refreshToken: refreshToken || null,
};

export const loginUser = createAsyncThunk(
  "api/login",
  async (payload, { rejectWithValue }) => {
    const url = HOST.concat("api/token/");
    return makeApiCall(url, "POST", payload, rejectWithValue);
  },
);

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    logout: (state) => {
      state.accessToken = null;
      state.refreshToken = null;
      state.username = null;
      state.password = null;
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
    },
    refresh: (state, action) => {
      state.refreshToken = action.payload.refresh;
      state.accessToken = action.payload.access;
    },
    setError: (state, action) => {
      state.error = action.payload;
      state.isLoading = false;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(loginUser.pending, (state, action) => {
        state.isLoading = true;
      })
      .addCase(loginUser.fulfilled, (state, action) => {
        state.accessToken = action.payload.access;
        state.refreshToken = action.payload.refresh;
        localStorage.setItem("accessToken", state.accessToken);
        localStorage.setItem("refreshToken", state.refreshToken);
        state.isLoading = false;
      })
      .addCase(loginUser.rejected, (state, action) => {
        state.error = action.payload;
        state.isLoading = false;
      });
  },
});

export const { logout, setError, refresh } = authSlice.actions;
export default authSlice.reducer;


Here my store configuration:

import { configureStore } from "@reduxjs/toolkit";
import { authSlice } from "./authSlice";
import { userSlice } from "./userSlice";

export const store = configureStore({
  reducer: {
    auth: authSlice.reducer,
    user: userSlice.reducer,
  },
});

and here my class http:

import axios from "axios";
import { store } from "../redux/store"; //Possible cause
import { HOST } from "./utils";

const getHeaders = () => {
  const headers = {
    Accept: "application/json",
    "Content-type": "Application/json",
  };
  const access = store.getState().auth.accessToken;
  if (access) {
    headers.Authorization = `Bearer ${access}`;
  }
  return headers;
};

const refreshAccessToken = async function () {
  return axios
    .request({
      method: "POST",
      url: HOST.concat("/api/v1/auth/refresh/"),
      data: {
        refresh: store.getState().auth.refreshToken,
      },
    })
    .then((response) => {
      if (response.status === 200) {
        store.dispatch({
          type: "auth/refresh",
          payload: response.data,
        });
      }
    })
    .catch(() => {
      store.dispatch({
        type: "auth/logout",
      });
    });
};

const axiosClient = axios.create();

axiosClient.interceptors.request.use(
  async (config) => {
    config.headers = getHeaders();
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

axiosClient.interceptors.response.use(
  (response) => {
    return response;
  },
  async function (error) {
    let response_status;
    try {
      response_status = error.response.status;
    } catch (e) {
      response_status = 200;
    }
    const originalRequest = error.config;
    if (response_status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      await refreshAccessToken();
      return axiosClient(originalRequest);
    }

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

export default async function makeApiCall(url, method, data, rejectWithValue) {
  return new Promise((resolve, reject) => {
    axiosClient
      .request({
        url,
        method,
        data,
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(rejectWithValue(error.response.data));
      });
  });
}

2

The error caused by a cyclic dependency between those 3 files

store imports segment -> segment imports http -> http imports store

One way to resolve this is to make the axios initialization a function with the store as a parameter and call it somewhere else instead of inside http

That way your http is decoupled from store

Separate out your implementation of store and your call for http. It is due to cyclic dependency and it’s not a good practice to keep cyclic dependencies in your app.

I think you have to wrap the App with Provider

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật