Reputation: 2804
I have a list with the following actions:
useReducer()
function.useReducer()
function.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});
});
Upvotes: 5
Views: 9487
Reputation: 53874
According to your code, your state is an Array
, make sure you preserve the type when returning it from useReducer
:
const reducer = (state, { type, value }) => {
switch (type) {
case 'replacenewarray':
// v Array as intended
return value;
case 'additem':
// v Fix it to return an array
return [...state, value];
// v Object
// return {...state, value}
case 'removeitem':
// v Array as intended
return state.filter(item => item.room !== value);
default:
return state;
}
};
Also, you must return a ReactElement
or Group
will not be considered as functional-component.
export const Group = memo(props => {
...
return <>Some React Element</>;
});
Upvotes: 2