Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to dispatch action outside component in Redux-Toolkit + typescript?

I have axis interceptor and I have in a store Error reducer. How to dispatch correctly action outside component ?

I tried store.dispatch, I don't know why but it crashes my whole store and my whole app is falling apart. I tried useAppDispatch, but get error can't use it outside component. Code below:

import axios from "axios";
import store from "../store/store";
import { addError } from "../store/errorSlice/errorSlice";

const instance = axios.create({
    timeout: 1000,
    withCredentials: true,
    baseURL: "http://localhost:8000"
})

instance.interceptors.response.use(response => response,
   function (error) {
        console.log("ERROR FROM SERVER");
        const { data, status } = error.response;
        const { message } = data;

        store.dispatch(addError({ message, status, active: true })) // crashes my whole app. It looks like triggering an action, but then delete all reducers
        return ;
})

export default instance;

here is my ErrorSlice.ts

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import IError from "../../models/error";

const initialState: IError = {
    message: "",
    status: 400,
    active: false
}

const ErrorSlice = createSlice({
    name: "Error",
    initialState,
    reducers: {
        addError: (_, action: PayloadAction<IError>) => action.payload,
        deleteError: (_) => {
            return { 
                message: "",
                status: 400,
                active: false } as IError   }
    }
})

export default ErrorSlice.reducer;
export const { addError, deleteError } = ErrorSlice.actions;
like image 453
Eldar Tailov Avatar asked Sep 16 '25 18:09

Eldar Tailov


1 Answers

You should never import the store directly into other application files, because you are likely to end up with a circular import dependency problem.

For this kind of use case, the best solution is to inject the file into the Axios setup logic at startup time, like this:

// axios-setup.js
let store

export const injectStore = _store => {
  store = _store
}

axiosInstance.interceptors.request.use(config => {
  config.headers.authorization = store.getState().auth.token
  return config
})

// index.js
import store from "./app/store".
import {injectStore} from "./axios-setup";
injectStore(store);
like image 117
markerikson Avatar answered Sep 19 '25 08:09

markerikson