I am building a matrix calculator as a react app. I have implemented a method that shows the history of every single mathematical operation that the user used, like addition, substraction etc. The problem is that every time a new operation is called and the current matrices change than the previous ones, the history updates its content with the new values.
You can test the app on: MatrixCalculator(Github)
The matrix itself is a class, where is defined a 2d array and its size
this.matrice = [];
for(let i=0;i<arraySize;i++){
this.matrice[i]= [];
for(let j=0;j<arraySize;j++){
this.matrice[i][j]=0;
}
}
this.size = arraySize;
Then to introduce the data to the matrix I use a form:
<input
type='text'
placeholder='0'
onChange={this.handleChange.bind(this, i, j)}
key={j}
/>
The function:
handleChange = (i,j, event)=> {
event.preventDefault();
let x = event.target.value;
this.state.matriceA.setValue(i, j, value);
}
By using this function, I insert the value to the matrix.
Now, every time an operation is requested, the matrices used, the operator and the matrix where the result is calculated are stored in an array. This is the function that does that:
var list = [
{
matrixA: matriceA,
operator: semn,
matrixB: matriceB,
matrixC: matriceC //result
}
]
this.setState({
results: [...list, ...this.state.results]
})
So, the values are now stored in this.state.results
and at the end I map through the entire array and display elements:
{this.props.rezultate.map((item, index) => {
///useless stuff
})}
But the elements shown are not expected to be there, here is an example:
To see, what i am talking about, look to the bottom of the page
As you can see, the last operation, also updated the previous operations, even though it should not have done that.
I do not know what i am doing wrong at this stage, so i am looking forward to hearing from you a solution. Thanks!