Shh
Shh

Reputation: 309

React JS Removing specific item from list

I have managed to create a list of friends and the addFriends function works correctly i.e a new person is added called 'New Friend' every time the button is pressed.

The removeFriend function also works but if I add a few friends then press Remove Friend it removes every item after the key rather than just the key itself. I want the code below to just remove key 2 (George Brown) rather than all records after it.

friendsActions.js

import * as f from '../constants'

export const addFriend = ({ firstname, lastname }) => ({
  type: f.ADD_FRIEND,
  frienditem: {
    firstname,
    lastname,
  },  
})

export const removeFriend = ({ key }) => ({
   type: f.REMOVE_FRIEND,
  key,
})

friendsReducer.js

import * as f from '../constants'

const initialState = [
  { firstname: 'John', lastname: 'Smith' },
  { firstname: 'James', lastname: 'Johnson' },
  { firstname: 'George', lastname: 'Brown' },
 ]

const friendsReducer = (state = initialState, action) => {
  switch (action.type) {
    case f.ADD_FRIEND:
      return [...state, action.frienditem] 
    case f.REMOVE_FRIEND:
      console.log('removing friend with key ' + action.key)
      return [...state.slice(0, action.key), ...state.slice(action.key + 1)]
    default:
       return state
  }
 }

export default friendsReducer

index.js (constants)

export const ADD_FRIEND = 'ADD_FRIEND'
export const REMOVE_FRIEND = 'REMOVE_FRIEND'

friendsContainer.js

import React from 'react'
import Page from '../components/Page'

import FriendList from '../containers/FriendList'

import { css } from 'glamor'

const FriendContainer = props => (
  <Page title="Friends List" colour="blue">
    <FriendList {...props} />
  </Page>
)

export default FriendContainer

friendsList.js

import React from 'react'
import { css } from 'glamor'

const Friend = ({ firstname, lastname }) => (
  <div>
    <ul>
      <li>
        {firstname} {lastname}
      </li>
    </ul>
  </div>
)

const FriendList = ({ friends, addFriend, removeFriend }) => (
  <div>
    <div>
      {friends.map((frn, i) => (
        <Friend key={++i} firstname={frn.firstname} lastname={frn.lastname} />
      ))}
    </div>
    <button onClick={() => addFriend({ firstname: 'New', lastname: 'Friend' })}>
      Add Friend
    </button>
    <button onClick={() => removeFriend({ key: '2' })}>Remove Friend</button>
  </div>
)

export default FriendList

Upvotes: 0

Views: 846

Answers (1)

Ivan
Ivan

Reputation: 10372

You are passing in a string as the key for the action:

{
  key: '3'
}

Then in your code, you add 1 to it, which is '31' in this case.

Change state.slice(action.key + 1) to state.slice(parseInt(action.key, 10) + 1) or change your keys to be numbers from the get-go.

Upvotes: 4

Related Questions