Home > Enterprise >  Multiple fetches with eventListener
Multiple fetches with eventListener

Time:10-16

Hello there I am struggling to find the solution of this 'bug'. I am not even sure why its happening? Using Giphy API the goal is to upload gif then save the id from response to the localStorage.The initial upload seem to work fine, however each next upload does a multiple fetches and adds in the localStorage more than one id for each gif. Will really appreciate any advice. Thanks!

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form>
      <input type="file" />
      <input type="submit" />
    </form>
    <div ></div>
    <script src="./fetch-api.js"></script>
  </body>
</html>

JavaScript:

const form = document.querySelector('form');
const inputFlie = document.querySelector('input');
const preview = document.querySelector('.tree');
const apiKey = 'yourapikeyhere'

form.addEventListener('change', () => {
  const uploadFile = new FormData();
  uploadFile.append('file', inputFlie.files[0]);

  const heads = {
    method: 'POST',
    api_key: apiKey ,
    body: uploadFile,
  };

  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    try {
      const send = await fetch(
        `https://upload.giphy.com/v1/gifs?api_key=${apiKey}`,
        heads
      );

      const feedback = await send.json();
      if (feedback.meta.status === 200) {
        form.reset();

        uploadID = feedback.data.id;
      }

      if (localStorage.getItem('uploaded') === null) {
        //if we don't create an empty array
        uploadedGifs = [];
        uploadedGifs.push(uploadID);
        localStorage.setItem('uploaded', JSON.stringify(uploadedGifs));
      } else {
        const currentItems = JSON.parse(localStorage.getItem('uploaded'));
        currentItems.push(uploadID);
        localStorage.setItem('uploaded', JSON.stringify(currentItems));
      }

      console.log(feedback);
    } catch (error) {
      console.log(error);
      statusMesage.textContent = 'Something went wrong!';
    }
  });
});

CodePudding user response:

separate event listeners, so as not to create a new one every time the form has been changed.

const form = document.querySelector('form');
const inputFlie = document.querySelector('input');
const preview = document.querySelector('.tree');
const apiKey = 'yourapikeyhere'
const heads = {
  method: 'POST',
  api_key: apiKey,
  body: null,
};

form.addEventListener('change', () => {
  const uploadFile = new FormData();
  uploadFile.append('file', inputFlie.files[0]);

  heads.body = uploadFile;
});

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  try {
    const send = await fetch(
      `https://upload.giphy.com/v1/gifs?api_key=${apiKey}`,
      heads
    );

    const feedback = await send.json();
    if (feedback.meta.status === 200) {
      form.reset();

      uploadID = feedback.data.id;
    }

    if (localStorage.getItem('uploaded') === null) {
      //if we don't create an empty array
      uploadedGifs = [];
      uploadedGifs.push(uploadID);
      localStorage.setItem('uploaded', JSON.stringify(uploadedGifs));
    } else {
      const currentItems = JSON.parse(localStorage.getItem('uploaded'));
      currentItems.push(uploadID);
      localStorage.setItem('uploaded', JSON.stringify(currentItems));
    }

    console.log(feedback);
  } catch (error) {
    console.log(error);
    statusMesage.textContent = 'Something went wrong!';
  }
});
  • Related