javascriptreactjsfirebasefirebase-realtime-databaseconfirm

Confirm Window in React


I have this following code :

renderPosts() {
return _.map(this.state.catalogue, (catalogue, key) => {
  return (
    <div className="item col-md-3" key={key} id={key}>
        <img src={this.state.catalogue[key].avatarURL} height={150} with={150}/>
        <h3>{catalogue.marque}</h3>
        <h4>{catalogue.numero}</h4>
        <h4>{catalogue.reference}</h4>
        <p>{catalogue.cote}</p>
        <div className="text-center">
        <button className="btn btn-danger" onClick={() => {if(window.confirm('Delete the item?')){this.removeToCollection.bind(this, key)};}}>Supprimer</button>
        </div>

    </div>
  )
 })
}

And I have this function too:

removeToCollection(key, e) {

  const item = key;
  firebase.database().ref(`catalogue/${item}`).remove();
 }

When I use the function without a confirm window in my "onclick" button, the code work great. But when I want use a confirm window, the confirm window show when I click on my button, but my item is not delete.

Any idea ?

Thank for your help !


Solution

  • Basically you're binding the function instead of calling it... you should bind beforehand, preferably in the constructor... then call it. Try this:

    renderPosts() {
      this.removeToCollection = this.removeToCollection.bind(this);
      return _.map(this.state.catalogue, (catalogue, key) => {
        return (
          <div className="item col-md-3" key={key} id={key}>
              <img src={this.state.catalogue[key].avatarURL} height={150} with={150}/>
              <h3>{catalogue.marque}</h3>
              <h4>{catalogue.numero}</h4>
              <h4>{catalogue.reference}</h4>
              <p>{catalogue.cote}</p>
              <div className="text-center">
              <button className="btn btn-danger" onClick={() => {if(window.confirm('Delete the item?')){this.removeToCollection(key, e)};}}>Supprimer</button>
              </div>
    
          </div>
        )
      })
    }