Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

258
Vistas
Remove all the elements of the array in React JS

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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 })
      })
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda