DEV Community

Cover image for Creating a Quote Generating Application using the Fetch API and DOM Manipulation.
Sarah Mukuti
Sarah Mukuti

Posted on

Creating a Quote Generating Application using the Fetch API and DOM Manipulation.

Introduction
JavaScript is a very dynamic web language and one of its great qualities is how it helps front-end developers consume API endpoints.In this article I will create a simple quote generating application based on a public API. The API link is [https://type.fit/api/quotes] you can explore it to understand the properties.
You will notice that the outer level of the data is an object nested within an array that contains other objects with specific author and quote properties.

The app uses the following concepts:

  • 1. DOM manipulation.
  • 2. Event listeners.
  • 3. Fetch API.
  • 4. CRUD

Create an empty folder where you will store the project.
The folder should have an index.js file and an index.html file. You can also have a style.css if you wish to add custom styling to the small application.
Add the following code block to make a fetch request.

fetch ('https://type.fit/api/quotes')
.then(res=>res.json())
.then(data=>{data.forEach(quoteObject => {.then(data=>{data.forEach(quoteObject => {
    const quoteList = document.getElementById('quote-list');
    const quoteEl = document.createElement('li');
    const spanAuthor = document.createElement('p');
    quoteEl.innerText = `${quoteObject.text}`;
    spanAuthor.innerText = `${quoteObject.author}`;
    spanAuthor.className = 'quote-span';
    quoteEl.appendChild(spanAuthor);
    quoteList.appendChild(quoteEl);
})
})
}
Enter fullscreen mode Exit fullscreen mode

The code block makes a call request then does DOM manipulation to display all the quotes and authors on the page.

After displaying all the quotes you can go ahead to randomly display a quote and the author.
You will have to apply the Math.floor(Math.random()
*data.length) methods to get a quote randomly from our array.
Then pass that quote and author to the html using DOM manipulation.

document.getElementById('new-quote').addEventListener('click', function (e){
    fetch('https://type.fit/api/quotes')
    .then(response=>response.json())
    .then (data => {
    const randomQuoteIndex = Math.floor(Math.random() * data.length);
    const quoteText = data[randomQuoteIndex].text;
    let author = data[randomQuoteIndex].author;
 quoteEl.textContent = quoteText;
    quoteAuthorEl.textContent = author;
}
)
Enter fullscreen mode Exit fullscreen mode

CRUD Operations.
CRUD is an abbreviation for create, read, update, and delete operations on a stored data object.
CRUD can also be termed as the basic operations that an application should be able to perform.
Update uses the verbs PUT, POST, and PATCH.
In the next part we will now create a db.json file within your project folder.
Then add the following coed block to POST new quotes to the json.
Before writing the code to postensure the server is running using the command json-server --watch db.json
Then make a POST request by adding the following header.
The code below creates a new quote and author post to our json server.

const post = {inputQuote, inputAuthor}
const configurationObject =   {
        method: 'POST', 
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(post),
      }
      fetch(url, configurationObject)
      .then(res=>res.json())
      .then(results=>
        console.log("successful addition"))
        e.target.reset()
})
Enter fullscreen mode Exit fullscreen mode

You can delete a record from the json file using the following code block.

function deleteQuote(){
document.getElementById('delete-form').addEventListener('submit', function(){
    const id = document.getElementById('id').value;
    fetch('http://localhost:3000/quotes/' + id, {
      method: 'DELETE',
    })
    .then(res => res.json()) // or res.json()
    .then(res => console.log(res))
})
    }
Enter fullscreen mode Exit fullscreen mode

Below is a link of the repository with the entire project code.
[https://github.com/cesarWrites/phase-1-project]

Top comments (0)