0

I'm trying to delete an item from a list in react native but its not working

handleDeletePost = (passedItem) => {
  const { userPosts } = this.state;
  const newArray = userPosts.map(item => {
  if (item.headline === passedItem.headline) {

  Alert.alert(
    'Delete Post',
    'Are you sure to delete Post?',
    [
      {text: 'Yes', onPress: () => console.log('Ask me later pressed')},
      {text: 'No', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}
    ],
    { cancelable: false }
  )
  }
});
}

When i hit delete i get an error: can't find variable index

2
  • Beside the error you get, not sure that's a good way to use map. It would be nice to try first to find the element you want to remove and the you Array.slice it out after onPress confirmation. Commented Dec 7, 2018 at 14:51
  • check if userPosts array is filled also use this.state.userPosts.map Commented Dec 7, 2018 at 14:52

1 Answer 1

1

Your map doesnt look like its being used corrently, but to remove an item from an array use the .splice() function.

EXAMPLE

var array = [2, 5, 9];
console.log(array)
var index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

OUTPUTS

array[2, 9]

Hope this helps :)

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

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.