Home > Back-end >  Redux toolkit Async Thunk: Cannot read properties of undefined
Redux toolkit Async Thunk: Cannot read properties of undefined

Time:12-02

I'm building a redux toolkit website, where i'll have a grid. So, to use this grid I am using the async thunk to fetch data from the back-end, and then send it to my redux slice. This code were working, but when I did a merge with another changes, it stopped. I already changed the default export to a common export default test = { ... }, then the error changed to "cannot access test before initialization".

My slice:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { AnyObject } from "../../models/utils/anyObject";
import { PageResponse } from "../../models/utils/pageResponse";
import thunk from "../thunks/grid";

interface GridState {
  data: PageResponse<AnyObject> | null;
  carregando: boolean;
  totalDeItems: number;
}

const initialState: GridState = {
  data: null,
  carregando: false,
  totalDeItems: 0,
};

const gridSlice = createSlice({
  name: "grid",
  initialState,
  reducers: {
    setCarregando: (state, action: PayloadAction<boolean>) => {
      state.carregando = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(thunk.getData.fulfilled, (state, { payload }) => {
      state.data = payload;
      state.totalDeItems = payload.totalItems;
    });
  },
});

export const gridActions = gridSlice.actions;
export default gridSlice;

My Thunk:

import { AsyncThunkAction, createAsyncThunk } from "@reduxjs/toolkit";
import { AnyObject } from "../../models/utils/anyObject";
import { PageOptions } from "../../models/utils/pageOptions";
import { PageResponse } from "../../models/utils/pageResponse";
import { gridActions } from "../slices/grid";

interface GridDataProps {
  thunk: (
    arg: PageOptions
  ) => AsyncThunkAction<PageResponse<AnyObject>, PageOptions, AnyObject>;
  options?: PageOptions;
}

export default {
  getData: createAsyncThunk(
    "grid/data",
    async (props: GridDataProps, { dispatch }) => {
      dispatch(gridActions.setCarregando(true));
      const response = await dispatch(
        props.thunk(
          props.options || {
            currentPage: 1,
            itemsPerPage: 4,
          }
        )
      );
      dispatch(gridActions.setCarregando(false));
      const result = response.payload as PageResponse<AnyObject>;
      return result;
    }
  ),
};

CodePudding user response:

I found the issue. I was dispatching an action to the gridSlice in my thunk, but the slice was importing the thunk too, so it generated a circular dependecy.

  • Related