Home > database >  Remove all the elements of the array in React JS
Remove all the elements of the array in React JS

Time:06-03

I have written a function which is triggered by a dropdown list's onChange event. Once the function is triggered, it load data from rest API according to the parameter value. However, the array which I have used to store those data is not cleared in the subsequent dropdown change events. As a result, when the user change the dropdown multiple times, the array grows with its previously loaded data.

for example: In first drop down change => ['A','B','C'] 2nd drop down change => ['A','B','C','E','F','G'] instead of ['E','F','G']

My code is as follows:

onDropdownChange = (e) => {
    var newArray = [];

// To remove all the elements of newArray
    newArray.forEach((e1,idx, arr) => {
      
        newArray.splice(idx,1);
      
    });

    console.log(newArray);
    const url = 'https://abcdefgh...../'   e   '/readings?today';
    newArray = this.state.data.slice();
    axios.get(url).then(res => {
      var response_arr = res.data.items;
      res.data.items.forEach((item, index) => {
        newArray.push({ time: res.data.items[index].dateTime, TM: res.data.items[index].value })
      })
      
     let sortedArray = newArray.sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime());
     this.setState({ data: sortedArray });
     this.fetchChart();
    });
  }
  fetchChart = () => {
    const { data } = this.state;
    return <CustomLineChart data={data} />
  }

  render(){
    const {items} = this.state;
    var data = [];
    const itemList = items.map(item => {
        return <tr key={item.dateTime '' item.value}>
            <td style={{whiteSpace: 'nowrap'}}>{item.dateTime}</td>
            <td>{item.measure}</td>
            <td>{item.value}</td>
        </tr>
    });
    return (
      <div>   
              {this.fetchChart()}
              <CustomDropdownList changeLink={this.onDropdownChange.bind(this)} />
              
      </div>
  );


  }
}

export default Dashboard;

Can anybody assist me to resolve this issue?

CodePudding user response:

You are copying the previous data with

newArray = this.state.data.slice();

You do not need that.. In fact you do not need any of this if you want to create a new array with new options.

CodePudding user response:

You're adding the results to newArray which starts out empty that you tried to clear, then it's set to the existing data with additional data added. Also, avoid using var.

var newArray = [];

    // This is already empty
    newArray.forEach((e1,idx, arr) => {
      
        newArray.splice(idx,1);
      
    });

    // This will always be empty
    console.log(newArray);

    const url = 'https://abcdefgh...../'   e   '/readings?today';

    // Existing data, remove this
    newArray = this.state.data.slice();
    axios.get(url).then(res => {
      var response_arr = res.data.items;
      res.data.items.forEach((item, index) => {

        // This is where new data is being added to existing
        newArray.push({ time: res.data.items[index].dateTime, TM: res.data.items[index].value })
      })
  • Related