Created
May 21, 2018 15:42
-
-
Save bookercodes/8b1f489dbdb200f07c29278bce56a2f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import { ChatManager, TokenProvider } from '@pusher/chatkit' | |
class MessageList extends Component { | |
render = () => ( | |
<ul> | |
{this.props.messages.map(message => ( | |
<li key={message.id}>{message.text}</li> | |
))} | |
</ul> | |
) | |
} | |
class MessageInput extends Component { | |
render = () => ( | |
<form | |
onSubmit={e => { | |
e.preventDefault() | |
this.props.onSubmit(this.inputEl.value) | |
this.inputEl.value = '' | |
}} | |
> | |
<input type="text" ref={el => (this.inputEl = el)} /> | |
<input type="submit" /> | |
</form> | |
) | |
} | |
class App extends Component { | |
state = { | |
messages: [] | |
} | |
componentDidMount = async () => { | |
const chatkit = new ChatManager({ | |
instanceLocator: 'v1:us1:e480b6f7-c2a7-4e60-ad6c-5b6fa330567d', | |
userId: 'Captain', | |
tokenProvider: new TokenProvider({ | |
url: | |
'https://us1.pusherplatform.io/services/chatkit_token_provider/v1/e480b6f7-c2a7-4e60-ad6c-5b6fa330567d/token' | |
}) | |
}) | |
this.currentUser = await chatkit.connect() | |
await this.subscribeToRoom() | |
} | |
subscribeToRoom = async () => { | |
await this.currentUser.subscribeToRoom({ | |
roomId: this.currentUser.rooms[0].id, | |
hooks: { | |
onNewMessage: message => { | |
this.setState({ | |
messages: [...this.state.messages, message] | |
}) | |
} | |
} | |
}) | |
} | |
sendMessage = async text => { | |
await this.currentUser.sendMessage({ | |
roomId: this.currentUser.rooms[0].id, | |
text | |
}) | |
} | |
render = () => ( | |
<div> | |
<MessageList messages={this.state.messages} /> | |
<MessageInput onSubmit={this.sendMessage} /> | |
</div> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment