This is my notesSlice:
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const url = "http://localhost:8000/";
const initialState = {
notices: [],
};
export const getNotices = createAsyncThunk(
"notices/getNotices",
async (_name, thunkAPI) => {
try {
const resp = await axios(`${url}notices`);
return resp.data;
} catch (error) {
return thunkAPI.rejectWithValue("something went wrong");
}
}
);
const noticesSlice = createSlice({
name: "notices",
initialState,
reducers: {
filterNotices: (state, { payload }) => {
console.log(state.notices)
console.log(payload)
if (payload.searchOption === "Simple") {
state.notices = state.notices.filter((note) =>
note.title.toLowerCase().includes(payload.search.toLowerCase())
);
} else if (payload.searchOption === "Advanced") {
state.notices = state.notices.filter(
(note) =>
note.description
.toLowerCase()
.includes(payload.search.toLowerCase()) ||
note.tags.filter((tag) => {
tag.toLowerCase().includes(payload.search.toLowerCase());
})
);
}
},
},
extraReducers: (builder) => {
builder
.addCase(getNotices.fulfilled, (state, { payload }) => {
state.notices = payload;
})
In payload of filterNotice
method, I am sending object with search
input and searchOption
. How should I search through all notices every time I call filterNotice
method? And is this even the correct way to do it?
2
Answers
Here’s the corrected version of your
filterNotices
reducer:Don’t mutate your source of truth by filtering it. The filtered result should be computed/derived "state" from the
notices
state and thesearch
value.If you don’t need to persist the filtered notices
Store the search type and value in state and use selector functions to compute the derived state.
The UI would dispatch the
setSearch
action to update the search value and use theuseSelector
hook andselectFilteredNotices
function to selected the filtered notices value.If you do need to persist the filtered notices in state
Create a new
filteredNotices
array in state, and when dispatching thefilterNotices
action you will filter the untouchedstate.notices
array and return/update thestate.filteredNotices
array. This leaves the original notices data intact.