3

My redux state looks like this (its synced with Firebase).

{
  profile: {
    activeUsers: {
      Iiva2BGZffNTH84glOLXv8QHVTF2: {
        sex: male,
        age: 20,
      },
      PkfMxrN09RN7ygoBMWqm4jheEOx1: {
        sex: female,
        age: 20,
      },
      zQiGXvcUGmRSKUdr719621QleUw2: {
        sex: male,
        age: 25,
      }
    }
  }
}

I want to remove user zQiGXvcUGmRSKUdr719621QleUw2

Heres my action creator

  Firebase.database()
    .ref('profiles/activeUsers')
    .on(
      'child_removed',
      (snapshot) => {
        dispatch(_activeUserChildRemoved(snapshot));
      },
      (err) => {
        console.log(err.toString());
        Alert.alert(err);
      },
    );
};

const _activeUserChildRemoved = snapshot => ({
  type: ACTIVE_USER_CHILD_REMOVED,
  payload: snapshot,
});

and finally here is my reducer

  switch (action.type) {
    case ACTIVE_USER_CHILD_REMOVED:
      const key4Del = action.payload.key;
      return { //what goes here??? };
    default:
      return state;
  }
};

What do i return from reducer in order to remove the user referenced by snapshot.key from redux? Help is much appreciated

james murphy
  • 491
  • 1
  • 10
  • 36
  • maybe this could help https://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object – muhsalaa Feb 13 '19 at 04:12

2 Answers2

2

Got it!!

case ACTIVE_USER_CHILD_REMOVED:
      const key4Del = action.payload.key;
      const oldState = state;
      delete oldState.activeUsers[key4Del];
      return { ...oldState };
james murphy
  • 491
  • 1
  • 10
  • 36
0

You need to remove the user by not mutating the state and simply by using destructuring.

Right now you're mutating the state directly by deleting object property from oldState

case ACTIVE_USER_CHILD_REMOVED:
  const key4Del = action.payload.key;
  const { [key4Del]: _, ...activeUsers} = state.activeUsers
  return {...state, activeUsers }

Spread Syntax will shallow compare the object, therefore you need to merge the filtered object again to generate a new state.

Pritish Vaidya
  • 18,941
  • 3
  • 43
  • 67