Part 3: Networking
No we're ready to provide the correct implementation for the fetchMessages()
function and the sendMessages()
function.
Getting Messages:
- Update the
fetchMessages()
function to use thefetch
API to get the messages from the server.- You'll need to remove the hardcoded array of images and replace it with a call to the server.
- URL to the Server is https://it3049c-chat.fly.dev
- URL to the link to get the messages is https://it3049c-chat.fly.dev/messages
- sometime, the server might be idle and would take a few minutes to wake up again.
💰 Solution (don't open until you really have to)...
Using Fetch API
- with `.then` callbacks
- with async/await
const serverURL = `https://it3049c-chat.fly.dev/messages`;
function fetchMessages() {
return fetch(serverURL)
.then( response => response.json())
}
const serverURL = `https://it3049c-chat.fly.dev/messages`;
function fetchMessages() {
const response = await fetch(serverURL);
return response.json();
}
- Where we're calling
fetchMessages()
in theupdateMessages()
, we need to make sure the function isasync
and weawait
the result fromfetchMessages()
.
💰 Solution (don't open until you really have to)...
async function updateMessages() {
// Fetch Messages
const messages = await fetchMessages();
// Loop over the messages. Inside the loop we will
// get each message
// format it
// add it to the chatbox
}
- try to log the
messages
variable to the console to confirm the structure of each message looks like this
{
"id": 1,
"text": "This is my message",
"timestamp": 1537410673072
}
- We need to make sure the function is called at least once when the page loads. We can do this by calling the function at the end of the script.
- otherwise, we won't see any difference.
updateMessages()
-
Use
setInterval()
to call this function once every 10 seconds to keep the new messages coming.setInterval(updateMessages, 10000);
- the number
10000
in this scenario is what we refer to as a magic number. it's a value of some significance but someone looking at this may not easily understand what this value is- we like to set this value to a variable to make this a bit more readable.
const MILLISECONDS_IN_TEN_SECONDS = 10000;
setInterval(updateMessages, MILLISECONDS_IN_TEN_SECONDS); - the number
Sending Messages
- Create a send function that would:
- take the username, and message text as parameter
- construct a json object with the following properties
sender
,text
, andtimestamp
- send messages to the server here
💰 Solution (don't open until you really have to)...
function sendMessages(username, text) {
const newMessage = {
sender: username,
text: text,
timestamp: new Date()
}
fetch (serverURL, {
method: `POST`,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newMessage)
});
}