Requests Ajax with the Fetch API keeps repeating

-1

I make an Ajax request with the Fetch API:

  function PostData() {

        var A1_CGC;
        A1_CGC = sessionStorage.getItem('cpf');
        console.log(A1_CGC)
        var inicio, fim, A1_CGC;

           inicio = document.getElementById('inicio').value;
           fim = document.getElementById('fim').value;

           // Default options are marked with *
           fetch('API_AQUI', {
               method: 'POST',
               headers: {'Content-Type':'application/x-www-form-urlencoded'},
               body: 'inicio=${inicio}&fim=${fim}&A1_CGC=${A1_CGC}'
           }).then(response => response.json().then(data => ({
               data: data,
               status: response.status
           })
           ).then(res => {
               res.data.map(element => {
                   var text = element.PRODUTO;
                   $('.produto-1').append('<h3>${element.PRODUTO}</h3>');

               })
               var ContaArray = res.data.length 
                if (!ContaArray) {
                    $('#MensagemZeroFiltro').append('<div class="alert alert-danger" role="alert">
                    Nenhuma compra nesse período de tempo.
                  </div>')
                }

           })
               )         
}

I put the start date and end date, and it brings some data by the date when I click the button, but if I click the button 3 times, it shows the result 3 times one below the other. I want it to stop showing more than once the result, I want it to show only once. Ex: I clicked the button to show the result, it showed, then I click again and nothing happens, but if I change the date, it should delete the previous result and put the new one. How do I solve this? I tried using stopImmediatePropagation(); but it did not work. I wish he would stop showing the contents repeatedly and show only once.

    
asked by anonymous 10.04.2018 / 15:22

2 answers

0

I was able to solve by throwing empty before starting the function fetch

function PostData() {

        var A1_CGC;
        A1_CGC = sessionStorage.getItem('cpf');

        var inicio, fim, A1_CGC;

           inicio = document.getElementById('inicio').value;
           fim = document.getElementById('fim').value;

           $('.produto-1').empty(); 

           // Default options are marked with *
           fetch('API_AQUI', {
               method: 'POST',
               headers: {'Content-Type':'application/x-www-form-urlencoded'},
               body: 'inicio=${inicio}&fim=${fim}&A1_CGC=${A1_CGC}'
           }).then(response => response.json().then(data => ({
               data: data,
               status: response.status
           })
           ).then(res => {
               res.data.map(element => {
                   var text = element.PRODUTO;
                   $('.produto-1').append('<h3>${element.PRODUTO}</h3>');

               })
               var ContaArray = res.data.length 
                if (!ContaArray) {
                    $('#MensagemZeroFiltro').append('<div class="alert alert-danger" role="alert">
                    Nenhuma compra nesse período de tempo.
                  </div>')
                }

           })
               )         
}
    
11.04.2018 / 14:38
0

You can create a function "with memory" that verifies if the values have changed before making a new request:

const PostData = (function() {
  let A1_CGC, inicio, fim, body, lastBody;
  const config = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
  };
  const erro = '<div class="alert alert-danger" role="alert">Nenhuma compra nesse período de tempo.</div>';
  return function() {
    A1_CGC = sessionStorage.getItem('cpf');
    inicio = document.getElementById('inicio').value;
    fim = document.getElementById('fim').value;
    body = 'inicio=${inicio}&fim=${fim}&A1_CGC=${A1_CGC}';

    // aqui fica a lógica para evitar pedidos duplicados
    if (body === lastBody) return;
    else lastBody = body;

    // Default options are marked with *
    fetch('API_AQUI', { ...config,
        body: body
      })
      .then(response => ({
        data: response.json(),
        status: response.status
      }))
      .then(res => {
        const produtos = res.data.reduce(
          (html, element) => '${html}<h3>${element.PRODUTO}</h3>', ''
        );

        if (produtos.length === 0) {
          $('#MensagemZeroFiltro').append(erro);
        } else {
          $('.produto-1').append(produtos);
        }
      });
  }
})();
    
11.04.2018 / 17:11