Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear states or empty array on click in react 0.14 ES6?

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: []
   })
 }
like image 917
Harsha Kakumanu Avatar asked Feb 17 '16 19:02

Harsha Kakumanu


4 Answers

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
like image 58
Harsha Kakumanu Avatar answered Sep 22 '22 15:09

Harsha Kakumanu


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([])
like image 33
leeCoder Avatar answered Sep 20 '22 15:09

leeCoder


A couple of solutions with explanations to this (albeit in ES5) can be found here:

https://stackoverflow.com/a/29994490/4572987

like image 39
dskoda1 Avatar answered Sep 20 '22 15:09

dskoda1


this.state.array.splice();

This will Delete or truncate whole array

like image 43
Tr4cEr Avatar answered Sep 23 '22 15:09

Tr4cEr