Reputation: 960
setState is not re-rendering the component or state is not updated at all
handleRowSelectPayrates = (status, nurseCert) => {
let { selectedCerts } = this.state
if (status) {
selectedCerts.push(nurseCert)
} else {
const index = selectedCerts.findIndex((s) => s.id == nurseCert.id)
if (index > -1) {
selectedCerts.splice(index, 1)
}
}
console.log(selectedCerts)
this.setState({ selectedCerts})
Above is the code which I am using to set the state. I am getting desired data in selectedCerificates
variable and even after that my state is also changing. But I am expecting my component to re-render.
I am not sure what I am missing. This code is used in some other places also where it is working fine. But here it is not.
Upvotes: 0
Views: 50
Reputation: 58593
The reason is, you are mutating state directly :
// you assigning state directly instead of copy of that
var selectedCertificates = this.state.selectedCerts; // <----- HERE
// this will update the state directly due to the above line
selectedCertificates.push(nurseCert)
// this also
selectedCerts.splice(index, 1)
Updated question
var {selectedCerts} = this.state
// selectedCerts is still pointing to state array, it's still not copy of array
State is already mutate/changed via push
and splice
, and then you are assigning the same state via this.setState
so as per react there is no change (b/w prev state that you updated and new value that you are passing), so it won't trigger the re-render.
Solution :
// you should pass the copy of array
var selectedCertificates = [...this.state.selectedCerts];
Upvotes: 1