Search code examples
javascripthtmlscriptingdynamic-html

How to use API instead of lengthy javascript?


Hey am new to javascript but putting my all efforts I have written a javascript that display some quotes with good pagination. But if I needed to upload some more quotes I need to edit the javascript itself. So I hava a api page where the quotes are in json format.

My API Page https://goodman456.000webhostapp.com/api.php Note: I have used the word status insted of quotes.

My html


 <div class="allquotes"></div>
<div class="pagable-status">
  <label>Page <span class="page-no-curr">1</span> of <span class="page-no-count">1</span></label>
  <div class="pagable-actions">
    <button class="page-btn-first">&#x226A;</button>
    <button class="page-btn-prev">&#60;</button>
    <input type="number" name="page-curr" min="1" value="1" />
    <button class="page-btn-next">&#62;</button>
    <button class="page-btn-last">&#x226B;</button>
    <select name="page-size">
      <option>5</option>
      <option>10</option>
      <option>20</option>
    </select>
  </div>
  <label>(<span class="result-count"></span> items)</label>
</div>

My Javascript

const resultEl = document.querySelector('.allquotes');
const pageSize = document.querySelector('select[name="page-size"]');
const pageCurr = document.querySelector('input[name="page-curr"]')
const resultCount = document.querySelector('.result-count')
const pageNoCurr = document.querySelector('.page-no-curr');
const pageNoCount = document.querySelector('.page-no-count')
const btnFirst = document.querySelector('.page-btn-first');
const btnPrev = document.querySelector('.page-btn-prev');
const btnNext = document.querySelector('.page-btn-next');
const btnLast = document.querySelector('.page-btn-last');

let results = [];

const getResultCount = () => results.length;
const getPageSize = () => +pageSize.value;
const getCurrPage = () => +pageCurr.value;
const getPageCount = () => Math.ceil(getResultCount() / getPageSize());

const pageResponse = (records, pageSize, page) =>
  (start => records.slice(start, Math.min(records.length, start + pageSize)))
  (pageSize * (page - 1));

const main = async() => {
  btnFirst.addEventListener('click', navFirst);
  btnPrev.addEventListener('click', navPrev);
  btnNext.addEventListener('click', navNext);
  btnLast.addEventListener('click', navLast);
  pageSize.addEventListener('change', changeCount);

  results = await retrieveAllQuotes();
  updatePager(results);
  redraw();
};
const redraw = () => {
  resultEl.innerHTML = '';
  const paged = pageResponse(results, getPageSize(), getCurrPage());
  const contents = document.createElement('div');
  contents.innerHTML = paged.map(record => `<div class='latestatus'><p class='copytxt'>${record.quotes}</p><div> <button class="copystatus btn">Copy</button></div></div>`).join('');
  resultEl.append(contents);
};

const navFirst = (e) => {
  pageNoCurr.textContent = 1;
  pageCurr.value = 1;
  redraw();
}

const navPrev = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const prevPage = curr > 1 ? curr - 1 : curr;
  pageCurr.value = prevPage;
  pageNoCurr.textContent = prevPage;
  redraw();
}

const navNext = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const nextPage = curr < pages ? curr + 1 : curr;
  pageCurr.value = nextPage;
  pageNoCurr.textContent = nextPage;
  redraw();
}

const navLast = (e) => {
  pageNoCurr.textContent = getPageCount();
  pageCurr.value = getPageCount();
  redraw();
}

const changeCount = () => {
  updatePager();
  redraw();
};

const updatePager = () => {
  const count = getPageCount();
  const curr = getCurrPage();
  pageCurr.value = curr > count ? 1 : curr;
  pageNoCurr.textContent = curr > count ? 1 : curr;
  pageNoCount.textContent = count;
  resultCount.textContent = getResultCount();
};

const retrieveAllQuotes = async function() {

  // write your asynchronous fetching here

  return[{
      quotes: "1The cat is better than dog."
    },
    {
      quotes: "2Google is a open source library."
    },
    {
      quotes: "3Cats are better than ferrets."
    },
    {
      quotes: "4Love books."
    },
    {
      quotes: "5Life is short make it possible."
    },
    {
      quotes: "6The cat is better than dog"
    },
    {
      quotes: "7Google is a open source library."
    },
    {
      quotes: "8Cats are better than ferrets."
    },
    {
      quotes: "9Love books."
    },
    {
      quotes: "10Life is short make it possible."
    },
]; 
}
main();

Did you notice this section

return[{
      quotes: "1The cat is better than dog."
    },
    {
      quotes: "2Google is a open source library."
    },
    {
      quotes: "3Cats are better than ferrets."
    },
    {
      quotes: "4Love books."
    },
    {
      quotes: "5Life is short make it possible."
    },
    {
      quotes: "6The cat is better than dog"
    },
    {
      quotes: "7Google is a open source library."
    },
    {
      quotes: "8Cats are better than ferrets."
    },
    {
      quotes: "9Love books."
    },
    {
      quotes: "10Life is short make it possible."
    },
]; 
}

I need to update quotes here. It's easy to me to edit the JSON file through php. So please modify the above javascript so that I can use my url.

So if any one can help please!!


Solution

  • The following should work just fine.

    const retrieveAllQuotes = async function() {
      // here we are making a network call to your api
      const response = await fetch('https://goodman456.000webhostapp.com/api.php');
      
      // then converting it to json instead of a readable stream
      const data = await response.json();
    
      // finally go over the array and return new object with renamed key
      const results = data.map(val => ({quotes: val.status}));
    
      return results;
    }
    

    Read about fetch and promises(async/await).