Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import SignalR in React Component?

I have used create-react-app to scaffold the initial react application.

My DashBoard component:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import $ from 'jquery';
import 'signalr';

class Dashboard extends Component {
   constructor(props) {    
   super(props);
   var connection = $.hubConnection('http://[address]:[port]');
   var proxy = connection.createHubProxy('[hubname]');   

    // atempt connection, and handle errors
    connection.start()
    .done(function(){ console.log('Now connected, connection ID=' + connection.id); })
    .fail(function(){ console.log('Could not connect'); });
}

  render() {
    return (...);
  }
}

export default Dashboard;

Now I get the below error from SignalR saying jQuery is not added, but I have imported it in the line above:

Error: jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.

If I comment out import "signalr"; jQuery gets loaded correctly and i can access the $ inside the module. Why does this happen?

like image 984
Mahbubur Rahman Avatar asked Sep 13 '17 06:09

Mahbubur Rahman


People also ask

How do you import SignalR in react?

import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import $ from 'jquery'; import 'signalr'; class Dashboard extends Component { constructor(props) { super(props); var connection = $. hubConnection('http://[address]:[port]'); var proxy = connection.

What is SignalR in react?

SignalR is a open-source library for Microsoft ASP.NET for server to send asynchronous notifications to client-side web applications. It comes with libraries both for server-side as well as client-side JavaScript. The JavaScript library of course can be used in a react web application.

How do I reconnect my SignalR?

Handle the disconnected event to display a message when an attempt to reconnect has timed out. In this scenario, the only way to re-establish a connection with the server again is to restart the SignalR connection by calling the Start method, which will create a new connection ID.

What is SignalR in react?

SignalR is a popular software library that allows you send server code to client-side applications, like a React application. This tutorial will show you how to install SignalR on both your ASP.NET Core and React Typescript application.

How do I import an element in react?

In React, importing is the same as in vanilla JavaScript. Let’s do a similar example to the one above, but instead of printing “Test Message” to the console, we’ll render it to the screen: In the file App.js automatically generated by the create-react-app command: Then, in a file called ImportElement.js in the same directory:

How can I send messages in a react app?

We went ahead and built a system where you can send messages in a React app. From there, it used SignalR to send the message to the ASP.NET Core app. Once the ASP.NET Core app got the message, it sent it's own message back to the React app.

How do I install SignalR in ASP NET Core?

Run the following command inside the Package Manager Console: This will install SignalR in your ASP.NET Core Application from the NuGet Package Library. Then open up your Startup.cs file and add the following line inside your ConfigureServices method: Next, create your SignalR hub. This will inherit the Hub class from the SignalR package.


1 Answers

This is how we do it now (year 2020) with the new package @microsoft/signalr. We use Redux, but you don't have to use Redux to be able to utilize this method.

If you are using @microsoft/signalr package instead of @aspnet/signalr, then this is how you can set it up. This is our working code in prod:

import {
  JsonHubProtocol,
  HubConnectionState,
  HubConnectionBuilder,
  LogLevel
} from '@microsoft/signalr';

const isDev = process.env.NODE_ENV === 'development';

const startSignalRConnection = async connection => {
  try {
    await connection.start();
    console.assert(connection.state === HubConnectionState.Connected);
    console.log('SignalR connection established');
  } catch (err) {
    console.assert(connection.state === HubConnectionState.Disconnected);
    console.error('SignalR Connection Error: ', err);
    setTimeout(() => startSignalRConnection(connection), 5000);
  }
};

// Set up a SignalR connection to the specified hub URL, and actionEventMap.
// actionEventMap should be an object mapping event names, to eventHandlers that will
// be dispatched with the message body.
export const setupSignalRConnection = (connectionHub, actionEventMap = {}, getAccessToken) => (dispatch, getState) => {
  const options = {
    logMessageContent: isDev,
    logger: isDev ? LogLevel.Warning : LogLevel.Error,
    accessTokenFactory: () => getAccessToken(getState())
  };
  // create the connection instance
  // withAutomaticReconnect will automatically try to reconnect
  // and generate a new socket connection if needed
  const connection = new HubConnectionBuilder()
    .withUrl(connectionHub, options)
    .withAutomaticReconnect()
    .withHubProtocol(new JsonHubProtocol())
    .configureLogging(LogLevel.Information)
    .build();

  // Note: to keep the connection open the serverTimeout should be
  // larger than the KeepAlive value that is set on the server
  // keepAliveIntervalInMilliseconds default is 15000 and we are using default
  // serverTimeoutInMilliseconds default is 30000 and we are using 60000 set below
  connection.serverTimeoutInMilliseconds = 60000;

  // re-establish the connection if connection dropped
  connection.onclose(error => {
    console.assert(connection.state === HubConnectionState.Disconnected);
    console.log('Connection closed due to error. Try refreshing this page to restart the connection', error);
  });

  connection.onreconnecting(error => {
    console.assert(connection.state === HubConnectionState.Reconnecting);
    console.log('Connection lost due to error. Reconnecting.', error);
  });

  connection.onreconnected(connectionId => {
    console.assert(connection.state === HubConnectionState.Connected);
    console.log('Connection reestablished. Connected with connectionId', connectionId);
  });

  startSignalRConnection(connection);

  connection.on('OnEvent', res => {
    const eventHandler = actionEventMap[res.eventType];
    eventHandler && dispatch(eventHandler(res));
  });

  return connection;
};

Then you would call like the following. Please note that this a pseudo code. You may have to call it differently depending on your project setup.

import { setupSignalRConnection } from 'fileAbove.js';

const connectionHub = '/hub/service/url/events';

export const setupEventsHub = setupSignalRConnection(connectionHub, {
  onMessageEvent: someMethod
}, getAccessToken);

export default () => dispatch => {
  dispatch(setupEventsHub); // dispatch is coming from Redux
};

Let me know if it helped by up-voting. Thank you

like image 94
xeiton Avatar answered Oct 25 '22 09:10

xeiton