@@ -23,8 +23,8 @@ const renderMessage = (e) => {
2323 div . appendChild ( timestamp )
2424
2525 messages . appendChild ( div )
26-
2726}
27+
2828const renderEmptyState = ( ) => {
2929 const messages = document . getElementById ( "messages" ) ;
3030
@@ -51,7 +51,7 @@ const fetchMessages = async () => {
5151 }
5252 data . forEach ( renderMessage )
5353 } catch {
54- console . log ( "check the url" )
54+ showError ( "Failed to load messages" ) ;
5555 }
5656}
5757
@@ -62,36 +62,41 @@ const sendMessage = async () => {
6262 const name = document . getElementById ( "user" ) . value . trim ( )
6363 const msg = document . getElementById ( "msg" ) . value . trim ( )
6464
65+ if ( ! name || ! msg ) {
66+ showError ( "Name and message are required" ) ;
67+ return ;
68+ }
69+
6570 const url = `${ BASE_URL } /message`
6671
67- const res = await fetch ( url , {
68- method : "POST" ,
69- headers : {
70- "Content-Type" : "application/json" ,
71- } ,
72- body : JSON . stringify ( {
73- name,
74- message : msg
72+ try {
73+ const res = await fetch ( url , {
74+ method : "POST" ,
75+ headers : {
76+ "Content-Type" : "application/json" ,
77+ } ,
78+ body : JSON . stringify ( {
79+ name,
80+ message : msg
81+ } )
7582 } )
76- } )
7783
78- let data ;
79- try {
80- data = await res . json ( ) ;
81- } catch {
82- data = { } ;
83- }
84- if ( ! res . ok ) {
85- showError ( data . error ) ;
86- return ;
87- }
84+ const data = await res . json ( ) ;
85+
86+ if ( ! res . ok ) {
87+ showError ( data . error ) ;
88+ return ;
89+ }
90+ document . getElementById ( "error" ) . textContent = "" ;
8891
89- document . getElementById ( "error" ) . textContent = "" ;
92+ document . getElementById ( "user" ) . value = ""
93+ document . getElementById ( "msg" ) . value = ""
9094
91- // fetchMessages() instead webSocket
92- document . getElementById ( "user" ) . value = ""
93- document . getElementById ( "msg" ) . value = ""
95+ } catch ( err ) {
96+ showError ( "Network error" ) ;
97+ }
9498}
99+
95100const button = document . getElementById ( "send-button" ) ;
96101button . addEventListener ( "click" , sendMessage )
97102
@@ -101,8 +106,7 @@ const showError = (msg) => {
101106 errorEl . style . color = "red" ;
102107} ;
103108
104- const ws = new
105- WebSocket ( WS_URL ) ;
109+ const ws = new WebSocket ( WS_URL ) ;
106110ws . onmessage = ( event ) => {
107111 const data = JSON . parse ( event . data ) ;
108112
0 commit comments