Skip to content

Instantly share code, notes, and snippets.

@Ibro
Created November 17, 2017 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ibro/b7c0972e39a62f2c5136f07ebd9b1d5e to your computer and use it in GitHub Desktop.
Save Ibro/b7c0972e39a62f2c5136f07ebd9b1d5e to your computer and use it in GitHub Desktop.
ASP.NET Core SignalR chat with React.js - https://codingblast.com/asp-net-core-signalr-chat-react
import React, { Component } from 'react';
import { HubConnection } from '@aspnet/signalr-client';
class Chat extends Component {
constructor(props) {
super(props);
this.state = {
nick: '',
message: '',
messages: [],
hubConnection: null,
};
}
componentDidMount = () => {
const nick = window.prompt('Your name:', 'John');
const hubConnection = new HubConnection('http://localhost:5000/chat');
this.setState({ hubConnection, nick }, () => {
this.state.hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
this.state.hubConnection.on('sendToAll', (nick, receivedMessage) => {
const text = `${nick}: ${receivedMessage}`;
const messages = this.state.messages.concat([text]);
this.setState({ messages });
});
});
}
render() {
return <div>Here goes chat</div>;
}
}
export default Chat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment