I have a list with the following actions:
- Add an Object into an array using
useReducer()
function. - Remove an Object from an array using
useReducer()
function. - Replace new array with old array using
useReducer()
function.
I need the best and safe way to update my list.
Currently I have done something like below, but it is not working properly.
const reducer = (state, {type, value}) => {
switch(type){
case 'replacenewarray':
return value;
case 'additem':
return {...state, value}
case 'removeitem':
return state.filter(item => item.room !== value);
default:
return state;
}
}
My functional component is as below:
const newArray = [
{room: 'someroomid1', ....},
{room: 'someroomid2', ....},
{room: 'someroomid3', ....}
];
const itemToAdd = {room: 'someroomid4', ....};
const itemToRemoveWithRoomId = 'someroomid2';
export const Group = memo(props=> {
const [list, setList] = useReducer(reducer, []);
setList({type: 'replacenewarray', value: newArray});
setList({type: 'additem', value: itemToAdd});
setList({type: 'removeitem', value: itemToRemoveWithRoomId});
});