Last active
November 21, 2018 11:09
-
-
Save harrisonmalone/d953617bc6d33577ba4252a94d3631a2 to your computer and use it in GitHub Desktop.
using .fetch and .then to access data from a rails api built together in class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
<link rel="stylesheet" href="style.css"> | |
<script defer src="main.js"></script> | |
</head> | |
<body> | |
<nav class="navigation"> | |
<a href="/">Home</a> | |
</nav> | |
<main> | |
<ul class="books"> | |
<p class="loader">loading books...</p> | |
</ul> | |
</main> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ul = document.querySelector('.books') | |
function fetchBooks() { | |
// get books | |
// url, options | |
const url = 'http://localhost:3000/books' | |
const request = fetch(url) //=> promise obj | |
return request.then(function(response) { | |
return response.json() | |
}) | |
} | |
fetchBooks() //=> promise | |
.then(function(books) { | |
ul.innerText = ''; | |
books.forEach(addBook) | |
}) | |
function addBook(book){ | |
const liBook = createBook(book) | |
ul.appendChild(liBook) | |
} | |
function createBook(book) { | |
// create the li wrapper for the book | |
const li = document.createElement('li') | |
li.classList.add('book') | |
// create the h4 title for the book | |
const title = document.createElement('h4') | |
title.innerText = book.title | |
const price = document.createElement('strong') | |
price.innerText = 'Price: ' | |
const priceArea = document.createElement('p') | |
priceArea.innerText = `$${(book.price / 100.00).toFixed(2)}` | |
// create p tag for the price | |
li.appendChild(title) | |
li.appendChild(priceArea) | |
priceArea.prepend(price) | |
return li | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
* { | |
margin: 0px; | |
font-family: sans-serif; | |
} | |
.navigation { | |
background: dodgerblue; | |
padding: 20px; | |
} | |
.navigation a { | |
text-decoration: none; | |
color: white; | |
font-size: 20px; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment