(INDEX) INDEX (2025)

Return to Angular (React and Vue)

   1:  // React
   2:  import { useEffect, useState } from 'react';
   3:   
   4:  function useSSE(url) {
   5:      const [message, setMessage] = useState(null);
   6:   
   7:      useEffect(() => {
   8:          const eventSource = new EventSource(url);
   9:   
  10:          eventSource.onmessage = (event) => {
  11:              setMessage(event.data);
  12:          };
  13:   
  14:          eventSource.onerror = (error) => {
  15:              console.error('SSE error:', error);
  16:          };
  17:   
  18:          return () => {
  19:              eventSource.close();
  20:          };
  21:      }, [url]);
  22:   
  23:      return message;
  24:  }
  25:   
  26:  // Component
  27:  function App() {
  28:      const message = useSSE('http://localhost:3000/sse');
  29:   
  30:      return (
  31:          <div>
  32:              {message && <div>{message}</div>}
  33:          </div>
  34:      );
  35:  }



   1:  // VUE
   2:  const sseMixin = {
   3:      data() {
   4:          return {
   5:              message: null,
   6:          };
   7:      },
   8:      created() {
   9:          this.eventSource = new EventSource('http://localhost:3000/sse');
  10:   
  11:          this.eventSource.onmessage = (event) => {
  12:              this.message = event.data;
  13:          };
  14:   
  15:          this.eventSource.onerror = (error) => {
  16:              console.error('SSE error:', error);
  17:          };
  18:      },
  19:      beforeDestroy() {
  20:          this.eventSource.close();
  21:      },
  22:  };
  23:   
  24:  // Component
  25:  new Vue({
  26:      el: '#app',
  27:      mixins: [sseMixin],
  28:      template: `
  29:          <div v-if="message">{{ message }}</div>
  30:      `,
  31:  });


Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23>  <24>  <25
Link to this page: http://www.vb-net.com/PushNotification/ReactVue.htm
<TAGS>  <ARTICLES>  <FRONT>  <CORE>  <MVC>  <ASP>  <NET>  <DATA>  <TASK>  <XML>  <KIOSK>  <NOTES>  <SQL>  <LINUX>  <MONO>  <FREEWARE>  <DOCS> <TRAVELS> <FLOWERS> <RESUME> < THANKS ME>