Ajax requests with the Fetch API keeps repeating

Asked

Viewed 191 times

-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 the end date, and it brings some data according to the date when I click the button, but if I click the button 3 times, it shows the result 3 times below the other. I want him to stop showing more than once the result, I want him to show it only once. Ex.: I clicked on the button to show the result, showed, then I click again and nothing happens, but if I change the date, it should delete the previous result and put the new. How do I fix it? I tried using stopImmediatePropagation(); but it didn’t work. I’d like him to stop repeatedly showing the contents and show only once.

  • Hello Maria, your question is not clear. When you say "it shows the result 3 times below each other" do you want this to happen? or just show the last result, or just the first? do you want me to fetch 3 times or wait for the first one?

  • Post a parole for this event $(".produto-1").append("<h3>${element.PRODUTO}</h3>");

  • Or you can subscribe to the result of the request: use $(".produto-1").html("<h3>${element.PRODUTO}</h3>"); Depending on the case you can even suspend sending requests by conditioning the function PostData() by checking the value of $(".produto-1")

  • @Sergio Atualizei a pergunta

  • @Atlasilva putting this it does not show all the results, shows only one, and there may be several

2 answers

0

I managed to solve by playing the 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>`)
                }

           })
               )         
}

0

You can create a "memory" function that checks if 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);
        }
      });
  }
})();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.