Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Creating new slice

...

1

...

.) Create

...

new folder

...

example: locationSlice)

...

2

...

.) Add boilerplate files

Add three files: api.js, index.js, and state.js.

...

3

...

.) Add initial state

Here, in the state.js, we are adding the initial state.

Code Block
export const initialState = {
  value: {
    location: {}
  etc: {},
};

...

4.) Add createSlice()

Create your slice in the index.js page.

Code Block
import { createSlice } from "@reduxjs/toolkit";

export const locationSlice = createSlice({
  name: "location",
  initialState,
  reducers: {
    addLocation: (state, action) => {
      state.value.push(action.payload);
    },
    deleteLocation: (state, action) => {
      state.value = state.value.filter((item) => item.id !== action.payload.id);
    },
  },
  extraReducers: {
  [getLocations.pending]: (state) => {
      state.loading = true;
    },
    [getLocations.fulfilled]: (state, { payload }) => {
      state.loading = false;
      state.etc = payload;
    },
    [getLocations.rejected]: (state) => {
      state.loading = false;
      state.error = true;
      state.errormessage = "";
    },
  },
});

...

5.) Create async thunk(for API logic)

Next, we are adding any API-related async thunks in the api.js page.

...

Afterwards, update the index.js page in the extraReducers section with getLocations[pending], getLocations[fulfilled], and getLocations[rejected]. This is added at Line 15-26.

Code Block
import { createSlice } from "@reduxjs/toolkit";

export const locationSlice = createSlice({
  name: "location",
  initialState,
  reducers: {
    addLocation: (state, action) => {
      state.value.push(action.payload);
    },
    deleteLocation: (state, action) => {
      state.value = state.value.filter((item) => item.id !== action.payload.id);
    },
  },
  extraReducers: { <-- HERE
  [getLocations.pending]: (state) => {
      state.loading = true;
    },
    [getLocations.fulfilled]: (state, { payload }) => {
      state.loading = false;
      state.etc = payload;
    },
    [getLocations.rejected]: (state) => {
      state.loading = false;
      state.error = true;
      state.errormessage = "";
    },
  },
});

...