I am creating delete functionality in my application. But somehow it is not behaving properly.
The initial state and reducer function is defined below:
import { createSlice } from '@reduxjs/toolkit';
const filterDataTemplate = {
programId: '',
year: '',
};
const initialState = {
//some other state
filterData: { ...filterDataTemplate },
};
const slice = createSlice({
name: 'editFilterSlice',
initialState: initialState,
reducers: {
updateFilterProgramId: (state, action) => {
return {
...state,
filterData: {
...state.filterData,
programId: action.payload,
},
};
},
updateFilterYear: (state, action) => {
return {
...state,
filterData: {
...state.filterData,
year: action.payload,
},
};
},
},
});
export const {
updateFilterYear,
updateFilterProgramId,
} = slice.actions;
export default slice.reducer;
And filter details is the object containing year and programId:
filterDetails: {year:2021, programId: "Ameria"}
And i want to achieve
filterDetails: {year:"", programId: ""}
So delete handler is stated below to achieve above criteria:
const handleDelete = (e) => {
e.preventDefault();
if (//some condition) {
dispatch(updateFilterYear(''));
console.log('filterdetails', filterDetails);
//filterDetails: {year:2021, programId: "Ameria"}
} else {
dispatch(updateFilterProgramId(''));
}
}.
//Outside handleDelete function
console.log('filterdetails', filterDetails);
//filterDetails: {year:"", programId: "Ameria"}
So filter details containg year and programId is obtained with the help of this code:
const filterDetails = useAppSelector(
(state) => state.locationsFilter.filterData
);
handleDelete function is getting called properly when I am clicking a button
But after running this code, the filter details is not updating first time but when I am again running the handler second time it is updating. And outside handleDelete it is showing correct value in the console but inside handleDelete console is showing correct value second time.
It is showing very strange behavior