How to clear data in specific state index using react js

Viewed 102

I need to create a function to clear the table row data on specific state index. This quite new for me. I know how to do this in jquery, however I work on javascript library. no error but the data is not clearing if I start clicking the button.

Goal set the value empty

Goal

Current Output

Current Output

Here is my Jsx code

<span className="fa  fa-minus" onClick={this.ClearRowData} index={i}></span>

ClearRowData Function

ClearRowData = async (index) => {
   
    const value = {
        customer: "",
        bank: "",
        branch: "",
        checkNo: "",
        checkDate: "",
        amount: "",
        remarks: "",
        
    }

    const rows = [...this.state.rows]
    var index = rows.indexOf(index)

    if(index !== -1) {
        this.setState({
            ...this.state.rows,
            value
        })
    }

}

Thanks

4 Answers

First of all, ClearRowData function shouldn't be an async function because you are not doing anything asynchronous inside it.

Assuming that this.state.rows is an array of objects similar to value defined in ClearRowData function, you can use map() method to update the state.

Inside the callback function of map() method, check if the index parameter's value is equal to the index passed to the callback function of the map() method as an argument; if they both are equal, then return the value object, otherwise return the current object as it is.

clearRowData = (index) => {
  
    const value = { ... };

    const updatedRows = this.state.rows.map((obj, i) => {
       return index == i ? value : obj;
    });
    
    this.setState({ rows: updatedRows });   
}

You also need to call clearRowData function correctly. Change

onClick={this.ClearRowData}

to

onClick={() => this.ClearRowData(i)}

It looks like you're expecting your i value to be passed to the function as a parameter, but it is not. It's being supplied as a property to the span element, which doesn't need it and ignores it. Instead the click event is being passed as a parameter.

If you don't want the event and just want your i value, pass it explicitly:

<span className="fa  fa-minus" onClick={() => this.ClearRowData(i)}></span>

Maybe this example can help you.

const clear = ( index ) => {
    setRows( rows.filter( row => row.id !== index ) )
}
Related