Giter Site home page Giter Site logo

react-signalr's Introduction

This hook is designed to be a proxy to the main HubConnection capabilities.

Build Status Known Vulnerabilities

Installation

npm install --save @known-as-bmf/react-signalr

You also need react (>= 16.8) and rxjs (>= 6) installed in your project.

Usage

const signalrEndpoint = 'https://...';

const MyComponent = () => {
  const [value, set] = useState<MyType>();

  const { send, on } = useSignalr(signalrEndpoint);

  useEffect(() => {
    const sub = on<MyType>('myMethod').pipe(debounceTime(200)).subscribe(set);

    return () => sub.unsubscribe();
  }, [on]);

  const notify = useCallback(() => {
    send('remoteMethod', { foo: 'bar' });
  }, []);
};

Connections are cached, it means that if you open a connection to an url, further calls to useSignalr with the same url will use the same connection.

When the last hook using a specific connection is unmounted, this connection is closed.

API

useSignalr

/**
 * Hook used to interact with a signalr connection.
 * Parameter changes (`hubUrl`, `options`) are not taken into account and will not rerender.
 * @param hubUrl - The URL of the signalr hub endpoint to connect to.
 * @param options - Options object to pass to connection builder.
 * @returns An object containing methods to interact with the hub connection.
 */
function useSignalr(
  hubUrl: string,
  options?: IHttpConnectionOptions
): UseSignalrHookResult;
interface UseSignalrHookResult {
  /**
   * Proxy to `HubConnection.invoke`.
   *
   * @typeparam TResponse - The expected response type.
   * @param methodName - The name of the server method to invoke.
   * @param arg - The argument used to invoke the server method.
   *
   * @returns A promise that resolves what `HubConnection.invoke` would have resolved.
   *
   * @see https://docs.microsoft.com/fr-fr/javascript/api/%40aspnet/signalr/hubconnection?view=signalr-js-latest#invoke
   */
  invoke: InvokeFunction;
  /**
   * Utility method used to subscribe to realtime events (`HubConnection.on`, `HubConnection.off`).
   *
   * @typeparam TMessage - The expected message type.
   * @param methodName - The name of the server method to subscribe to.
   *
   * @returns An observable that emits every time a realtime message is recieved.
   *
   * @see https://docs.microsoft.com/fr-fr/javascript/api/%40aspnet/signalr/hubconnection?view=signalr-js-latest#on
   * @see https://docs.microsoft.com/fr-fr/javascript/api/%40aspnet/signalr/hubconnection?view=signalr-js-latest#off
   */
  on: OnFunction;
  /**
   * Proxy to `HubConnection.send`
   *
   * @param methodName - The name of the server method to invoke.
   * @param arg - The argument used to invoke the server method.
   *
   * @returns A promise that resolves when `HubConnection.send` would have resolved.
   *
   * @see https://docs.microsoft.com/fr-fr/javascript/api/%40aspnet/signalr/hubconnection?view=signalr-js-latest#send
   */
  send: SendFunction;
}

SendFunction

type SendFunction = (methodName: string, arg?: unknown) => Promise<void>;

InvokeFunction

type InvokeFunction = <TResponse = unknown>(
  methodName: string,
  arg?: unknown
) => Promise<TResponse>;

OnFunction

type OnFunction = <TMessage = unknown>(
  methodName: string
) => Observable<TMessage>;

react-signalr's People

Contributors

avertj avatar known-as-bmf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-signalr's Issues

Invoking a method with no parameters returns arguments error

If I invoke a method with no parameters, I get the following error:

Uncaught (in promise) Error: Failed to invoke 'getConnectionId' due to an error on the server. InvalidDataException: Invocation provides 1 argument(s) but target expects 0.

Client code:

    const connectionId = invoke('getConnectionId')
        .then(function (connectionId) {
            console.log("connection ID", connectionId);
        });

Server code in hub:

    public string GetConnectionId()
    {
        return Context.ConnectionId;
    }

However, if I add a fake parameter to the server method, it works, e.g:

    public string GetConnectionId(object dummy)
    {
        return Context.ConnectionId;
    }

I have tried passing null and undefined to the client args param but to no avail.

Expose connection state

Hi
Is it possible to expose also the state of connection so we can use that to know when we are connected /disconnected ?

Passing headers - not working?

Note: I am using version: 1.0.7-beta.2 and 6.0.0 of @microsoft/signalr.

Hi, in my React project, client side I use:

const {on} = useSignalr(${configFile.values.signalRUrl}/hubs/k3Menu, { headers: {"foo": "bar"} });

And server side:
` public override Task OnConnectedAsync()
{
var httpCtx = Context.GetHttpContext();
var foo = httpCtx.Request.Headers["foo"].ToString();

        return base.OnConnectedAsync();
    }`

But it's not being received. Checking the network tab, the headers aren't being passed. Am I doing something wrong? Or does websockets not support them? If I set the logLevel in the options it's reflected in the console so I am using the right object/syntax it seems.

(Apologies but the code doesn't seem to want to format correctly.)

Thanks!

TypeError: Object(...) is not a function

Hi,

Thanks for this :)

I have a small issue, when I run everything localhost all runs smooth and no hassel.

After deployment I get this error:

TypeError: Object(...) is not a function
at react-signalr.esm.js:211
at CriminalRecordInfo.js:34
at ss (react-dom.production.min.js:5142)
at kl (react-dom.production.min.js:6494)
at t.unstable_runWithPriority (scheduler.production.min.js:309)
at Go (react-dom.production.min.js:2816)
at Sl (react-dom.production.min.js:6474)
at ul (react-dom.production.min.js:5870)
at react-dom.production.min.js:2851
at t.unstable_runWithPriority (scheduler.production.min.js:309)

If I Chrome debug i think this is the breaking point - I tried looking through code to se what's up, but no luck.

react-signalr.esm.js (Breaks in this file)
return fromEventPattern(sub, unsub); (This line)

Im using the hook like this: (Edit out names for security)

useEffect(() => {
const letterStatus = on("METHODNAME").pipe(debounceTime(200)).subscribe(useStateSetMethod);
return () => letterStatus.unsubscribe();
}, [on])

Renew token after expired token

Hi,
I'm looking for a solution to refresh an old access_token.
Currently i use:

const { on, state } = useSignalr(
  'myUrl...',
    {
        httpClient: httpClient
    }
  );

and httpClient:

class SignalrClient extends DefaultHttpClient {
 ...
    public async send(
        request: signalR.HttpRequest
    ): Promise<signalR.HttpResponse> {
       // get accees token
        request.headers = {
            Authorization: `Bearer ....`
        };
        return super.send(request);
    }
}

it works fine, but this solution is not elegant so I want to use accessTokenFactory..
I tryed beta version and useed :

 const { on, state } = useSignalr(
        `${baseConfiguration.tracker_hub_url}/route/`,
        {
            accessTokenFactory: () => oidcUser.access_token
        }
    );
 useEffect(() => {
        if (state == HubConnectionState.Disconnected) {
            console.log('HubConnectionState.Disconnected');

        }
    }, [state]);

but I have no ide how to refresh accessTokenFactory

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.