Creating new slice
1.) Create new folder
example: features/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 |
---|
import { createAsyncThunk } from "@reduxjs/toolkit"; export const getLocations = createAsyncThunk( "steps/getLocations", async ({ id }, thunkAPI) => { const res = await fetch( `https://locationsAPI.com/${id}` ).then((data) => data.json()); return res; } ); |
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
by importing the action, as well as updating the extraReducers
.
Code Block |
---|
import { createSlice } from "@reduxjs/toolkit"; import { getLocations } from "./api"; 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 = ""; }, }, }); |
Line 2
: Import the getLocations()
action.
Line 15-27
: Update the index.js
page in the extraReducers
section with getLocations[pending]
, getLocations[fulfilled]
, and getLocations[rejected]
6.) Add the slice to Store
Code Block |
---|
import locationSlice from "./features/location/locationSlice";
export const store = configureStore({
reducer: {
filter: filterSlice,
steps: stepSlice,
location: locationSlice
},
}); |