Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda