Search code examples
javascriptfetchresponse

How to use the second input that sets the limit for displayed images on the fetch request?


There are two inputs, the first one is responsible for the displayed image from the data[0] array, the second input is responsible for the number of displayed images per page, both inputs have a limit from 1 to 10, please help to add the fetch request so that the second input is correctly used

HTML:

<input placeholder="page number" class="number">
<input placeholder="limit" class="limit">
<button class="button">SUBMIT</button>
<div class="output"></div>

JS:

function loadPage() {
  let num = document.querySelector('.number')
  let lim = document.querySelector('.limit')
  let btn = document.querySelector('.button')
  let out = document.querySelector('.output')
  function request() {
    if((num.value < 10 && num.value > 0) && (lim.value < 10 && lim.value > 0)) {
      fetch(`https://picsum.photos/v2/list?page=${num.value}&limit=${lim.value}`)
      .then(response => {
        return response.json()
      })
      .then(data => {
        out.innerHTML = `
          <img src="${data[0].download_url}" width="200px" height="200px">
          <div>${data[0].author}</div>
        `
      })
    } else {
      out.innerHTML = 'number out of range'
    }
  }
  btn.addEventListener('click', request)
}
document.addEventListener('click', loadPage)

Solution

  • Could you please add some further details in what you're looking for? Perhaps explain a bit more about what the expected behaviour would be, and what happens right now.

    When I run your code and enter a value above 0 and below 10, I do get a response back with an image and a name.