JAVASCRIPT

Consume Real-time API Data using WebSockets in JavaScript

Learn to integrate WebSockets in a frontend JavaScript application to receive and display real-time updates from an API, enhancing user experience.

// Ensure your WebSocket server is running at this URL
const websocketUrl = 'ws://localhost:8080/ws'; // Replace with your actual WebSocket endpoint

let ws;

function connectWebSocket() {
  ws = new WebSocket(websocketUrl);

  ws.onopen = () => {
    console.log('WebSocket connected!');
    document.getElementById('status').textContent = 'Status: Connected';
    // You can send initial messages to the server if needed
    // ws.send('Hello from client!');
  };

  ws.onmessage = (event) => {
    console.log('Received message:', event.data);
    const dataDisplay = document.getElementById('realtime-data');
    const newEntry = document.createElement('p');
    try {
      const jsonData = JSON.parse(event.data);
      newEntry.textContent = `Timestamp: ${new Date().toLocaleTimeString()} | Data: ${JSON.stringify(jsonData)}`;
    } catch (e) {
      newEntry.textContent = `Timestamp: ${new Date().toLocaleTimeString()} | Raw: ${event.data}`;
    }
    dataDisplay.prepend(newEntry); // Add new data to the top
  };

  ws.onclose = (event) => {
    console.log('WebSocket disconnected:', event.reason);
    document.getElementById('status').textContent = `Status: Disconnected (${event.code})`;
    // Attempt to reconnect after a delay
    setTimeout(connectWebSocket, 3000);
  };

  ws.onerror = (error) => {
    console.error('WebSocket error:', error);
    document.getElementById('status').textContent = 'Status: Error';
  };
}

// Initial connection
connectWebSocket();

// Basic HTML structure for context (not part of the JS snippet but implied)
/*
<div id="status">Status: Connecting...</div>
<div id="realtime-data" style="max-height: 300px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px;">
  <!-- Real-time data will appear here -->
</div>
*/
How it works: This JavaScript snippet demonstrates how to establish and manage a WebSocket connection in a client-side web application. It sets up event listeners for `onopen`, `onmessage`, `onclose`, and `onerror` to handle connection status, incoming real-time data, disconnections, and errors. Upon receiving data, it parses and displays it, and includes basic reconnection logic to maintain a persistent connection, crucial for real-time dashboards or chat applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs