How to remove an array from another array in redux state javascript

Viewed 72

I have the following data :

removed_users = [1]

And

userProfile = [{id:1 , user:{id:1,username:test}} ,
               {id:2 , user:{id:2,username:test2}} ,]

What i wish to do: I wish to be able to remove the correct objects from userProfile , based on the array removed_users . I have tried the following code below but its not removing it from the array

state.project['userProfile'].filter(function(user) {
                                                    return !action.payload.find(function(removed) {
                                                            return removed === user.user.id
                                                                    })
                                                                })}

This is the code for the reducer thats supposed to help me remove the removed_users from the state

        case 'user_remove': return (updateObject(state, {
        project: {...state.project , ['users']:  state.project['userProfile'].filter(function(user) {
                                                                    return !action.payload.find(function(removed) {
                                                                    return removed === user.user.id
                                                                    })
                                                                })}
    }))

This is the script for updateObject helper function:

export const updateObject = (oldObject, updatedProperties) => {
return {
    ...oldObject,
    ...updatedProperties
}

}

3 Answers

Try this to remove user:

const userProfile = [
  {id:1 , user:{id:1,username:"t1"}} ,
               {id:2 , user:{id:2,username:"t2"}}]

const arr= [1];
const filtered = userProfile.filter(({user})=> !arr.includes(user.id)); 
console.log(filtered)

Steps:

  1. Dispatch an action for deleting a user by its id.
function removeUser(id){
   return {
     type: "REMOVE_USER",
     payload: id
   }
}
dispatch(removeUser(1))
  1. Filter users in the reducer that the users id is not equal with received id. And then set new filtered users in the state which not include removed users.
function reducer(state, action){
   switch(action.type){
     case "REMOVE_USER":
        return {
          ...state,
          users: state.users.filter(user => user.id !== action.payload),
        }
     // other cases
   }
}

Good luck.

Related