Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[READY] Feat/98: add websocket hook #104

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

baliyan9887
Copy link
Contributor

@baliyan9887 baliyan9887 commented Jan 28, 2025

Pull Request Description:

Summary:

This pull request introduces a new useWebSocket() hook to React Haiku, enabling easy management of WebSocket connections in React applications.

Features:

  • WebSocket Connection Management
  • Auto-Reconnect
  • Callbacks for Custom Behavior.
  • Exposes a send method to send messages via the WebSocket.

Usage

import React from 'react';
import { useWebSocket } from 'react-haiku';

const WebSocketComponent = () => {
  const { lastMessage, status, sendMessage } = useWebSocket('wss://example.com/socket', {
    maxReconnectAttempts: 3,
    reconnectDelay: (attempt) => Math.min(5000, Math.pow(2, attempt) * 1000),
    onOpen: () => console.log('Connected to WebSocket'),
    onMessage: (message) => console.log('Received message:', message),
    onError: (error) => console.error('WebSocket error:', error),
    onClose: (event) => console.log('WebSocket closed:', event),
  });

  return (
    <div>
      <h1>WebSocket Hook</h1>
      <p>Status: {status}</p>
      <button onClick={() => sendMessage('Hello, Server!')}>Send Message</button>
      <p>Received Data: {lastMessage}</p>
    </div>
  );
};

Screenshot

image

@baliyan9887 baliyan9887 changed the title Feat/98 add websocket hook Feat/98: add websocket hook Jan 28, 2025
@DavidHDev
Copy link
Owner

Could you write some tests to cover this hook please?

@DavidHDev
Copy link
Owner

Also, don't forget to update out index.ts file to ensure the hook is exported

@baliyan9887
Copy link
Contributor Author

Sure David, I'll do

@DavidHDev
Copy link
Owner

Thank you, will mark this as ready for release.

@DavidHDev DavidHDev changed the title Feat/98: add websocket hook [READY] Feat/98: add websocket hook Feb 1, 2025
@baliyan9887
Copy link
Contributor Author

Thanks David!

@baliyan9887
Copy link
Contributor Author

@DavidHDev I have also added the demo page

@DavidHDev
Copy link
Owner

Looks great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants