I have a form in react which has the problem that when adding the next element the list is updated to the values of the last element added to it.
//import ReactDOM from "react-dom";
//import React, { Component, Fragment } from "react";
class Todo extends React.Component {
state = {
data_object: {
item: "",
select: ""
},
times: []
};
getNames = e => {
let data_object = this.state.data_object;
data_object[e.target.name] = e.target.value;
};
getSelect = e => {
let data_object = this.state.data_object;
data_object[e.target.name] = e.target.value;
};
addItem = e => {
e.preventDefault();
let obj = this.state.data_object;
this.setState({
times: this.state.times.concat(obj)
});
};
edit = (e, index) => {
console.log("edit", index);
let edit_element = this.state.times[index];
console.log(edit_element);
};
render() {
console.log(this.state.times);
let get_times = this.state.times.map((value, index) => {
return (
<li key={index} style={{ marginTop: "10px" }}>
{value.item} - {value.select}
<button
style={{
background: "#50d890",
padding: "3px",
color: "#FFF",
borderRadius: "5px",
marginLeft: "5px",
paddingLeft: "5px",
paddingRight: "5px",
border: "black"
}}
>
Editar
</button>
<button
style={{
background: "#f0134d",
padding: "3px",
color: "#FFF",
borderRadius: "5px",
marginLeft: "5px",
paddingLeft: "5px",
paddingRight: "5px",
border: "black"
}}
>
X
</button>
</li>
);
});
return (
<div>
<form>
<input name="item" onChange={e => this.getNames(e)} />
<select name="select" onChange={e => this.getSelect(e)}>
<option>No Requerido</option>
<option>Requerido</option>
</select>
<button onClick={e => this.addItem(e)}>Añade otro</button>
</form>
<div>
<h4>Mis Tiempos:</h4>
<ul>{get_times}</ul>
</div>
</div>
);
}
}
ReactDOM.render(<Todo />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I already saw the problem, it is that when adding item I was not cleaning the states of data_object so this is like this: