Home > front end >  When add new row in table, old data is beeing like new
When add new row in table, old data is beeing like new

Time:01-18

I create a table, where we can add new row with inputs.Thats see like this

I have 2 components: AddNewRow, which have some inputs for write new data, and TableComponent, which keep data about all rows.

TableComponent:

addRow(rowData){
    let newData = this.state.data
    console.log(newData)
    newData.push(rowData)
    console.log(newData)
    this.setState({data: newData})
}

render() {
    return(
        <Table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    </tr>
            </thead>
            <tbody>
                {this.state.data.map(row =>{
                    if (row.changeMode){
                        return(<ChangeRow key={row.id} inputData={row} changeMode={this.changeMode} changeData={this.changeData}/>)
                    }
                    else{
                        return (<TableRow key={row.id} data={row} changeMode={this.changeMode} deleteRow={this.deleteRow}/>)
                    }
                })}
                <AddNewRow rowData={{changeMode: false, id: '', name: ''}} addRow={this.addRow}/>
            </tbody>
        </Table>  
    )
}

AddNewRow:

export default function AddNewRow({rowData, addRow}){
    const [row, setRow] = useState(rowData)

    const changeCell = (e, index) =>{
        let newRow = row
        let key = Object.keys(newRow)[index]
        newRow[key] = e.target.value
        setRow(newRow)
    }

    return(
        <tr>
            {Object.keys(row).map((key, index) => {
                if(key != 'changeMode'){
                    return <td><Input onChange={e => changeCell(e, index)}/></td>
                }}
            )}
            <td><Button color='primary' onClick={() => {
                addRow(row)}
            }>Add</Button></td>
        </tr>
    )
}

And when I add a new row, old data is beeing as new.

CodePudding user response:

In the changeCell you're mutating state (changing the same object) something you should avoid when dealing with state. You should make a copy of it.

let newRow = { ...row };
  • Related