(React 16.8.6) I have the problem that when a variable change, it automatically changes also the state even if I don't call any setState. In the handleInputChange when I assign the value, it automatically updates the states clientsData and editedClientsData . I would like to update only editedClientsData.
Here is the code:
1 - set the state (fired on a button click):
getClients(calls) {
axios.all(calls)
.then(responseArr => {
let cleanedDate = []
responseArr.map(el => {
cleanedDate.push(el.data.data)
})
this.setState({
clientsData: cleanedDate,
editedClientsData: cleanedDate,
loading: false
})
this.loadDataChart()
});
}
2 - load the inputs fields
render(){
return (...
this.state.editedClientsData.map(this.renderInput)
...)
}
renderInput = (client, i) => {
const { activeYear } = this.state
return (<tr key={client.id}>
<td>{client.name}</td>
<td><Input
type="number"
name={client.id}
id="exampleNumber"
placeholder="number placeholder"
value={client.chartData[activeYear].r}
onChange={this.handleInputChange}
/></td>
<td>{client.chartData[activeYear].x}</td>
<td>{client.chartData[activeYear].y}</td>
</tr>
)
}
handleInputChange(event) {
let inputs = this.state.editedClientsData.slice();
const { activeYear } = this.state
for (let i in inputs) {
if (inputs[i].id == event.target.name) {
inputs[i].chartData[activeYear]['r'] = parseFloat(event.target.value)
console.log(inputs)
// this.setState({ editedClientsData: inputs })
break;
}
}
}
I tried to assign a fixed number I tried to save as const {clientsData} = this.state , updating editedClientsData and the this.setState({clientsData})
All of these tests failed. Hope in your helps, thank you!
for .. in
loop doesn't make sense, are you trying to modify each value in the array? – Claritylet { editedClientsData } = this.state
const { clientsData, activeYear } = this.state
editedClientsData[index].chartData[activeYear][data] = parseFloat(event.target.value)
But also this code failed.. I had the same wrong result. – f.strazzante