Created
January 9, 2021 17:14
-
-
Save arthur-littm/e9baa07ee8481af002ec9b82adbe8025 to your computer and use it in GitHub Desktop.
This file contains 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 batch = 476; // change to your own batch id | |
const baseUrl = "https://wagon-chat.herokuapp.com/"; | |
const url = baseUrl + batch + "/messages"; | |
const list = document.querySelector('#messages ul'); | |
// Your turn to code! | |
// 1. listen to the form and step 2 when you submit | |
const form = document.querySelector('#comment-form'); | |
const message = document.getElementById('your-message'); | |
const name = document.getElementById('your-name'); | |
form.addEventListener('submit', (event) => { | |
event.preventDefault(); | |
// 2. collect the message and the name | |
console.log(message.value) | |
console.log(name.value) | |
// 3. put in a Object () | |
const messageBody = { | |
author: name.value, | |
content: message.value | |
} | |
// 4. fetch to post our message | |
fetch(url, { | |
method: 'POST', | |
headers: { "Content-Type": "application/json" }, | |
body: JSON.stringify(messageBody) | |
}) | |
.then(response => response.json()) | |
.then((data) => { | |
console.log(data); | |
}); | |
}); | |
// 1. event listener for the refresh button | |
const button = document.getElementById('refresh'); | |
button.addEventListener('click', (e) => { | |
// 2. get the messages from the api (using fetch) | |
fetch(url) | |
.then(response => response.json()) | |
.then((data) => { | |
console.log(data); | |
list.innerHTML = ""; | |
// 3. insert the messages inside the page | |
data.messages.forEach((message) => { | |
// something for each message | |
const timeAgo = Math.round((new Date() - new Date(message.created_at)) / 60000) | |
const li = `<li>${message.content} (posted <span class="date">${timeAgo} minutes ago</span>) by ${message.author}</li>` | |
console.log(message) | |
list.insertAdjacentHTML('beforeend', li) | |
}) | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment