I am trying to add bill into the billItems state using redux Toolkit and I don't want to have multiple same bill with the same Id in the billItems. Each bill is like {billId: 5, billName: "string"}. I made many attempts but nothing work as I want
First Attempt
export const billSlice = createSlice({
name: "bill",
initialState: {
billItems: [],
},
reducers: (state, action) => {
const arr = [...state.billItems];
if (arr.length === 0) {
state.billItems = [...arr, action.payload];
} else {
const filteredArr = arr.filter(
(item) => item.productId !== action.payload.productId
);
state.billItems = [...filteredArr, action.payload];
}
},
});
With this attempt when I make may dispatch it just change the previous bill and replace by the new one which is not the needed result
Second attempt I decide to keep lastBill in the initialSate, take all billItems state with multiple same bill and go to filter it in the selector using lastBill property. in the selector like this
export const bSlice = createSlice({
name: "bill",
initialState: {
lastBill: {},
billItems: [],
},
reducers: (state, action) => {
state.billItems = [...state.billItems, action.payload]
});
And my selector is like
const billItems = useSelector(state => {
const arr = state.billItems
const lastBill = state.lastBill
const lastBill_Id = state.lastBill.lastBillId
if(arr.length === 0){
return [...arr, lastBill]
}else{
// I filter to obtain a new array whithout any instance of the lastBill
const filteredArr = arr.filter(item => item.billId !== lastBill_Id)
// I push now the lastBill to be sure that it is unique in the array and return it
return [...filteredArr, lastBill]
}
} )
But with this attempt when i populated the store with the same bill, the store save it then I have many same bills in the state billItems which is not the needed result
There something that I don't undersatnd. please i need your help
after many research, I have an issue for this. the problem was the reference of objects in Javascripts. I make change in the billSlice like this.
[add_to_billItems_action.fulfilled]: (state, action) => {
let arr = state.billItems;
if (arr.length === 0) {
// I make a copy of arr and modify billItems. At that time arr and billItems have the same payload
state.billItems = [...arr, action.payload];
arr = state.billItems;
} else {
let filteredArr = arr.filter((item) => item.id !== action.payload.id);
state.billItems = [...filteredArr, action.payload];
}