I am rendering an array in a modal. Once the modal closes I need to empty the array.The following code updates the array but not clear array on click of closeModal.
constructor(props,context) {
super(props,context);
this.state = {
myArray: []
};
}
pushData(newVar) {
this.setState((state) => {
myArray: state.myArray.push(newVar)
});
}
closeModal() {
this.setState({
myArray: []
})
}
I found the problem is my closeModal didn’t get called at all on closing modal. I am doing that to closeModal on componentWillUnmount function. I understood that the below code causes problem.
this.state.myArray=[] // class component
const[myArray, setMyArray]=useState([]) // functional component
I changed it back to
this.setState({myArray: []}); // class component
setMyArray([]); // functional component
You can as well use this to clear array without using setState:
this.state.your_array.length = 0;
This will work in any function.
Update Functional component:
setYourArray([])
A couple of solutions with explanations to this (albeit in ES5) can be found here:
https://stackoverflow.com/a/29994490/4572987
this.state.array.splice();
This will Delete or truncate whole array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With