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

47,858

Solution 1

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

Solution 2

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([])

Solution 3

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

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

Solution 4

This is what worked for me.
Class based component

this.setState({myArray: []});

With React Hook,

const [myArray, setMayArray] = React.useState([]);
setMayArray([]);

Solution 5

this.state.array.splice();

This will Delete or truncate whole array

Share:
47,858
Harsha Kakumanu
Author by

Harsha Kakumanu

Updated on July 09, 2022

Comments

  • Harsha Kakumanu
    Harsha Kakumanu almost 2 years

    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: []
       })
     }
    
  • dskoda1
    dskoda1 about 8 years
    So the pushData method correctly adds newVar into the state and causes a re-render correct? why not make those methods uniform and have closeModal look like: this.setState((state) => { myArray: [] });
  • dskoda1
    dskoda1 about 8 years
    If that doesn't work, I suspect it has something to do with the code changing the actual reference React has to the myArray variable, and as a result not affecting it at all..
  • Carl Vitullo
    Carl Vitullo about 8 years
    Never assign to this.state outside of the constructor. That might fix your immediate problem but it will cause bugs.
  • Gaston Sanchez
    Gaston Sanchez about 8 years
    Yes, use this.setState({ myArray: [] }); instead.
  • Safeer
    Safeer almost 2 years
    This will not update the state, also splice needs two params: 1. start The zero-based location in the array from which to start removing 2. deleteCount The number of elements to remove