Search code examples
javascriptreactjstypescriptreact-tablereact-table-v7

Why is my react Table not updating the data?


I got a react Table that I want to delete or modify my data. My code is below for all my cells.

    deleteTableElement = (row) => {
        let data = this.state.list.data;
        data.splice(row.id, 1);
        this.setState({
            list:{
                ...this.state.list,
                data:data
            }
        })
    };

    actionsCell = (columns) => {
        columns.push({
            Header: "Accion",
            Cell: (props) => {
                console.log(props);
                return (
                    <div
                        style={{
                            display: "flex",
                            justifyContent: "space-around",
                        }}
                    >
                        <i
                            onClick={() => this.deleteTableElement(props.row)}
                            className="material-icons"
                            style={{ color: "red", cursor: "pointer" }}
                        >
                            delete
                        </i>
                    </div>
                );
            },
        });
        return columns;
    };

In this case, I want to modify the item. The react table is not updating.


Solution

  • Whenever your component unexpectedly doesn't update, it's because you're mutating state. Literally 100% of the time:

            let data = this.state.list.data;
            data.splice(row.id, 1); // <- splice mutates an array, mutating state is bad
            this.setState({
                list:{
                    ...this.state.list,
                    data:data
                }
            })
    

    should be:

            this.setState({
                list:{
                    ...this.state.list,
                    data:data.filter((d,i) => i !== row.id)
                }
            })