Redux Toolkit TypeScript BaseClass

Viewed 15

I create BaseClass Reducer for CRUD.

const initialState: BaseState = {
  isLoading: true,
  objectsArray: [],
  errorDescription: "",
}

export class CRUDReducer {
    readonly nameSlice: string = 'default';
    readonly urlSlice: string = 'default';

    constructor(nameSlice: string, url: string) {
        this.nameSlice = nameSlice;
        this.urlSlice = url;
    }

    getListAsync: any = createAsyncThunk<{}, KeyValuePair[], {state: RootState}>(
        `${this.nameSlice}/getList`,
        async (urlParams: KeyValuePair[]) => {
            let url = `api/${this.urlSlice}`;
            const getResult = await Http.get(url);

            return getResult;
        }
    )
    reducerSlice = createSlice({
        name: this.nameSlice,
        initialState,
        reducers: {
        },
        extraReducers: {
            [this.getListAsync.pending]: (state) => {
                state.isLoading = true;
            },
            [this.getListAsync.fulfilled]: (state, action) => {
                if (
                    action.payload.error !== undefined &&
                    action.payload.error != null
                ) {
                    state.errorDescription = action.payload.errorDescription;
                } else {
                    state.objectsArray = action.payload.result;
                    state.paginator = action.payload.paginator;
                }
                state.isLoading = false;
            },
            [this.getListAsync.rejected]: (state, action) => {
                console.error(this.nameSlice + '/getListError', action);
                state.isLoading = false;
                state.errorDescription =
                    'Error! Try again';
            },
    });
}

In my store slices I use this CRUDReducer

import { RootState } from '../store';
import { CRUDReducer } from './CRUDReducer';

const baseReducer = new CRUDReducer(
    'accountParkingPlaces',
    'parking/places'
);

export const { getListAsync, createAsync, updateAsync, deleteAsync } =
    baseReducer;

const accountParkingPlacesSlice: any = baseReducer.reducerSlice;

export const selectList = (state: RootState) => state.accountParkingPlaces.objectsArray;
export const selectIsLoading = (state: RootState ) => state.accountParkingPlaces.isLoading;

export default accountParkingPlacesSlice.reducer;

But each call slice with CRUDReducer overwrites values in all state. It doesn't matter which slice I access (for example state.accountParkingPlaces.objectsArray ) the value will be taken from the last slice called

0 Answers
Related