Muhammad
Muhammad

Reputation: 2804

What is the best way to update state using useReducer function hooks?

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});


});

Upvotes: 5

Views: 9487

Answers (1)

Dennis Vash
Dennis Vash

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

Related Questions