Skip to main content

Part 3: Networking

No we're ready to provide the correct implementation for the fetchMessages() function and the sendMessages() function.

Getting Messages:

  1. Update the fetchMessages() function to use the fetch API to get the messages from the server.
💰 Solution (don't open until you really have to)...

Using Fetch API

const serverURL = `https://it3049c-chat.fly.dev/messages`;

function fetchMessages() {
return fetch(serverURL)
.then( response => response.json())
}

  1. Where we're calling fetchMessages() in the updateMessages(), we need to make sure the function is async and we await the result from fetchMessages().
💰 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
}

  1. 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()

  1. 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);

Sending Messages

  1. Create a send function that would:
    • take the username, and message text as parameter
    • construct a json object with the following properties sender, text, and timestamp
    • 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)
});
}