5

I have a list with the following actions:

  1. Add an Object into an array using useReducer() function.
  2. Remove an Object from an array using useReducer() function.
  3. 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});


});
Muhammad
  • 2,572
  • 4
  • 24
  • 46
  • What is the issue you are facing with this code? – Jaisa Ram Sep 22 '19 at 17:28
  • I would declare the shape of the state somewhere in the reducer so it helps to understand more the code, also I would follow the example from here https://reactjs.org/docs/hooks-reference.html#usereducer – darmis Sep 22 '19 at 19:43

1 Answers1

2

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</>;
});
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • I can't guess how you read the `list` and how your application is structured, moreover you using `React.memo`, there is a chance your component not even rendered after `dispatch` – Dennis Vash Sep 22 '19 at 19:50