C
C
colorkid2021-09-05 11:44:25
redux
colorkid, 2021-09-05 11:44:25

How to get rid of code duplication in redux?

Hello!
I write several reducers using the redux toolkit like this:

const initialState = {
  loading: false,
  data: [],
  errors: {},
};

const keyNameSlice = createSlice({
  name: "keyName",
  initialState,
  reducers: {
    setLoader: (state) => {
      state.loading = true;
      state.errors = initialState.errors;
    },
    setData: (state, action) => {
      const { payload } = action;
      state.loading = false;
      state.data = payload;
    },
    setError: (state, action) => {
      const { payload } = action;
      state.loading = false;
      state.errors = payload;
    },
  },
});


and such code is duplicated from reducer to reducer, i.e. pretty simple logic for getting data from api.
How to write such a piece 1 time and use it everywhere? type useFetch but in redux(toolkit)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question