Pavindu
Pavindu

Reputation: 3123

React Native modal is not updated when Redux state is changed using hooks

I have a modal component in my React Native mobile app. It receives an array of objects from Redux state. I can delete a specific item in the array using dispatching an action using useDispatch hook. However, after sending the delete action, the component state is not updated automatically, so that I have to reopen the modal every time to see the updated list.

How can I set the modal to automatically re-render when the redux state is changed using dispatch?

SelectedItems.js

const SelectedItems = () => {
  const vegetables = useSelector(state => state.new_order.vegetables)

  return (
<Modal visible={isVisible}>
  {vegetables.map( (v,index) => 
     <VegeItem 
      key={index}
      index={index}
      name={v.name}
      qty={v.qty}
      metric={v.metric}
      removeItem={(index) => {
        dispatch({
          type: 'DELETE_VEGE',
          id: index
        })
      }}
   />)}
 </View>
</Modal>  
  )
}

newOrderReducer.js

  const newOrderReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
      case 'ADD_VEGE':
        let updatedList = [...state.vegetables,action.vege]
        return {
          ...state,
          vegetables: updatedList
        }
      case 'DELETE_VEGE':
        let newVegeList = state.vegetables
        newVegeList.splice(action.id,1)
        return {
            ...state,
            vegetables: newVegeList
        }
      default:
        return state
    }
  };

Upvotes: 2

Views: 1130

Answers (1)

Hagai Harari
Hagai Harari

Reputation: 2877

while doing like so let newVegeList = state.vegetables, newVegeList is just a pointer on your state and not a shallow copy of it. Therefore, you still can't mutate it as you can't mutate state outside the return part of the reducer.

so you can do like let newVegeList = [...state.vegetables], or directly at the return

    return {
        ...state,
        vegetables: state.vegetables.filter((veg, i) => i != action.id)
    }

you can also send veg name or whatever and modify the checker at filter

Upvotes: 1

Related Questions