Advertisement
Liliana797979

messenger - js applicatons

Nov 10th, 2021
1,068
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.     // add event listener to load button
  3.     document.getElementById('refresh').addEventListener('click', loadMessages);
  4.     // add event listener to post button
  5.     document.getElementById('submit').addEventListener('click', onSubmit);
  6.     loadMessages();
  7. }
  8. const authorInput = document.querySelector('[name="author"]').value;
  9. const contentInput = document.querySelector('[name="content"]').value;
  10. const list = document.getElementById('messages');
  11.  
  12. attachEvents();
  13.  
  14. //add single message to list
  15. async function onSubmit() {
  16.     const author = authorInput.value;
  17.     const content = contentInput.value;
  18.  
  19.     const result = await(createMessage({author, content}));
  20.  
  21.     contentInput.value = '';
  22.     list.value += '\n' + `${author}: ${content}`;
  23. }
  24.  
  25. //load and display all messages
  26. async function loadMessages() {
  27.     const url = `http://localhost:3030/jsonstore/messenger`;
  28.     const res = await fetch(url);
  29.     const data = await res.json();
  30.  
  31.     const messages = Object.values(data);
  32.     const list = document.getElementById('messages');
  33.     list.value = messages.map(m => `${m.author}: ${m.content}`).join(`\n`);
  34. }
  35. //post message
  36. async function createMessage(message) {
  37.     const url = `http://localhost:3030/jsonstore/messenger`;
  38.     const options = {
  39.         method: 'post',
  40.         headers: {
  41.             'Content-Type': 'application/json'
  42.         },
  43.         body: JSON.stringify(message)
  44.     };
  45.     const res = await fetch(url, options);
  46.     const result = await res.json();
  47.  
  48.     return result;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement