0

I have a problem with my code. I currently have some data like the one below;

 users: [
    {
      name: 'bolu',
      features: ['Tall'],
    },
    {
      name: 'cam',
      features: ['Bearded', 'Short'],
    },
  ],
};

What I am trying to do is delete/remove a single feature - for example if I pass in 'short' into my redux action. I'd like for it (the 'Short' text) to be removed from the features array. I currently have my redux action set up this way:

export interface UsersDataState {
  name: string,
  features: Array<string>,
}

export interface UsersState {
  users: UsersDataState[];
}

const initialState: UsersState = {
  users: [],
};

    export const usersSlice = createSlice({
      name: 'users',
      initialState,
      reducers: {
        removeUser: (state, action: PayloadAction<string>) => {
          const removedUsers = state.users.filter((user) => user.features.indexOf(action.payload));
          state.users = removedUsers;
        },
       },
   });

So here I am passing in the value in (action.payload is the value being passed in). When this action is dispatched, I want to remove just the word that is passed in from the features array. I hope this is clearer now.

This doesn't work for some reason and I am unable to figure out why. Any help would be appreciated please, thank you.

2
  • Could you please be more specific? Do you want to: 1. Remove the feature e.g. 'Short' from all users in store? 2. Remove the feature from a particular user? Commented Mar 16, 2022 at 19:58
  • I’m voting to close this question because this is a repeat of a question that was only asked 40 minutes ago. Commented Mar 16, 2022 at 20:09

2 Answers 2

1

You need to copy the objects on users and filter on features.

Here an example:

var users = [{
  name: 'bolu',
  features: ['Tall'],
}, {
  name: 'cam',
  features: ['Bearded', 'Short'],
}];

const payload = "Short";

const newUsers = users.map(user => ({ ...user,
  features: user.features.filter(f => f != payload)
}));

console.log(newUsers);

Sign up to request clarification or add additional context in comments.

Comments

0

Currently you are filtering users array but you should be filtering nested features array.

Try this

const removedUsers = state.users.map(user => {
  return {...user, features: user.features.filter(feature => feature !== action.payload)};
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.