0

I'm having trouble with removing an object from an array. I have tried many options and nothing works. Please help me solve this problem.

Thanks for your help

My array:

export const SavedList = [
    {
      word: 'hello',
      translate: 'привет',
      note: 'say say'
    }
]

Remove callback (deletePost)

class Menu extends Component {
  state = { 
    word: '',
    translate: '',
    note: '',
    data: SavedList,
  }
  deletePost =(id)=>{
    this.setState({
      data : this.state.data.filter((el)=> el.id !== id)
    })
  }
  render() {
    return (
          <div className="content">
            <Routes>
              <Route path="/" element={<Layout />}>
                  <Route path="saved" element={<Saved data={this.state.data} del={this.deletePost}/>}/>
              </Route>
            </Routes>
            <div>
            </div>
        </div>
    );
  }
}
export default Menu;

here button delete with onClick

class Saved extends Component {
  render() {
    const sl = this.props.data.map((sl, id) => {
      return (
        <div className="saved-card" key={id}>
          <div className="content">
            <p>{id}</p>
            <p>{sl.word}</p>
            <p>{sl.translate}</p>
            <p>{sl.note}</p>
          </div>
          <div className="btn-block">
            <button
              onClick={() => this.props.del(id)}
              type="button"
              className="delete-btn"
            >
              delete
            </button>
          </div>
        </div>
      );
    });
    return (
      <div>
        <h2>Saved list</h2>
        <div className="saved-inner">
          <div className="saved-list">{sl}</div>
        </div>
      </div>
    );
  }
}

export default Saved;
0

1 Answer 1

2

This issue is because el.id doesn't have any value in delete Post Function. That function also needs to have an ID variable, I have named it as i_di.

class App extends Component {
  state = { 
    word: '',
    translate: '',
    note: '',
    data: SavedList,
  }
  deletePost =(id)=>{
    this.setState({
      data : this.state.data.filter((el, i_di)=> i_di !== id )
    })
  }
  render() {
    return (
          <div className="content">
              {<Saved data={this.state.data} del={this.deletePost}/>}
            
        </div>
    );
  }
}
export default App;

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.