1
\$\begingroup\$

I'm learning AJAX JSON. I'm just testing how to pull the data. The idea is, when hovering over the number, it pulls the data and show the content for name and email. Number 1 is to show name and number 2 is to show email.

The api is working, but I'm not quite sure how to refactor or make the code less redundant. Right now I just duplicate the code from one to another. I tried to add callback function, but I feel I'm doing it wrong.

const button = document.querySelector(".testName");
const buttonTest = document.querySelector(".testLastName");

const wrapper = document.querySelector(".wrapper");

const randomPerson = document.querySelector("random-person");



button.addEventListener("mouseover", function () {
    getData("https://randomuser.me/api/");
    console.log("first name");
})

buttonTest.addEventListener("mouseover", function () {
    getDataTest("https://randomuser.me/api/");
    console.log("last name");
})

function getData(url) {
    const request = new XMLHttpRequest();

    request.open("GET", url, true);
    //console.log(request);

    request.onload = function () {
        if (this.status === 200) {
            const data = JSON.parse(this.responseText);
            console.log(data);

            let display = "";

            data.results.forEach(function (person) {
                display += `
                    <div class="person">
                        <img class="random-image-js" src=${person.picture.large}></img>
                        <div class="person-category">
                            <p>Name: <br> ${person.name.first}</p>
                        </div>
                        
                        
                    </div>`
            });

      

            //randomPerson.innerHTML = display;

            wrapper.innerHTML = display;

        }
        else {
            console.log(this.statusText);
        }
    }

    request.onerror = function () {
        console.log("There was a mistake");
    }

    request.send();
}

function getDataTest(url) {
    const request = new XMLHttpRequest();

    request.open("GET", url, true);
    //console.log(request);

    request.onload = function () {
        if (this.status === 200) {
            const data = JSON.parse(this.responseText);
            console.log(data);

            let display = "";

            data.results.forEach(function (person) {
                display += `
                    <div class="person">
                        <img class="random-image-js" src=${person.picture.large}></img>
                        <div class="person-category">
                            <p>Email: <br> ${person.email}</p>
                        </div>
                    </div>`
            });

            wrapper.innerHTML = display;

        }
        else {
            console.log(this.statusText);
        }
    }

    request.onerror = function () {
        console.log("There was a mistake");
    }

    request.send();
}
body {
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}

.random-wrapper {
  border: 1px solid green;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.random-wrapper .random-image-generator {
  width: auto;
  border-radius: 0;
}

.random-image-js {
  width: 150px;
  border-radius: 50%;
}

.random-button {
  border: 1px solid green;
  padding: 10px 30px;

  background-color: #7305e4;
  color: #ffffff;
  cursor: pointer;
}

.random-title-generator {
  border: 1px solid green;
  width: 100%;
  text-align: center;
  padding: 10px 0;
  margin: 0;
  background-color: #839367;
  color: #ffffff;
}

.random-button:hover {
  background-color: #5d1579;
}

.random-button:focus {
  outline: none;
}

.wrapper {
  border: 1px solid green;
  width: 100%;
  margin-top: 50px;
}

.person {
  width: 1000px;
  border: 1px solid green;
  margin: auto;
  text-align: center;
}

.person-category {
  display: flex;
  justify-content: center;
}

.person-category p {
  display: flex;
  flex-direction: column;
  margin: 15px;
}

.test {
  display: flex;
}

.test p {
  padding: 20px;
  border: 1px solid green;
}
<div class="random-wrapper">
  <div class="wrapper"></div>

  <div class="test">
       <p class="testName">1</p>
       <p class="testLastName">2</p>
  </div>
</div>

\$\endgroup\$
  • \$\begingroup\$ "I tried to add callback function, but I feel I'm doing it wrong." - anyways it's better than duplicating the code. Go ahead \$\endgroup\$ – Bohdan Stupak Oct 25 '19 at 9:27
  • \$\begingroup\$ @BohdanStupak Yes, I already add callback function, but still not quite sure how to call each of the data. Right now it's just duplicating \$\endgroup\$ – Udzzzz Oct 25 '19 at 13:28
1
\$\begingroup\$
  • Find the differences and extract them into separate functions that you can pass as a parameter to the common processing function
  • Use modern syntax: async/await, fetch, for-of, destructuring assignment
const wrapper = document.querySelector('.wrapper');
const fieldDefinitions = {
  '.test': {
    Name: person => person.name.first,
  },
  '.testLastName': {
    Email: person => person.email,
  }
};
for (const [selector, fields] of Object.entries(fieldDefinitions)) {
  document.querySelector(selector).onmouseover = () => addPerson(fields);
}

async function addPerson(fields) {
  try {
    const {results} = await (await fetch('https://randomuser.me/api/')).json();
    const htmlChunks = results.map(person => `
      <div class="person">
        <img class="random-image-js" src="${person.picture.large}">
        <div class="person-category">${
          Object.entries(fields)
            .map(([name, fn]) => `<p>${name}:<br>${fn(person)}</p>`)
            .join('')
        }</div>
      </div>
    `);
    wrapper.insertAdjacentHTML('beforeend', htmlChunks.join(''));
  } catch (e) {
    console.debug(e);
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.