Commit 442fbfaa authored by Dave Brudner's avatar Dave Brudner Committed by Joe Haddad

Update with-socket.io example (#9583)

* Using custom hook instead of `_app.js` to interface with
`socket.io-client`
parent 9bf48687
...@@ -33,4 +33,4 @@ yarn dev ...@@ -33,4 +33,4 @@ yarn dev
## The idea behind the example ## The idea behind the example
This example show how to use [socket.io](https://socket.io/) inside a Next.js application. It uses `getInitialProps` to fetch the old messages from a HTTP endpoint as if it was a Rest API. The example combine the WebSocket server with the Next server, in a production application you should split them as different services. This example shows how to use [socket.io](https://socket.io/) inside a Next.js application using a custom hook. The example combines the WebSocket server with the Next server. In a production application you should consider splitting them into different services.
import { useEffect } from 'react'
import io from 'socket.io-client'
const socket = io()
export default function useSocket(eventName, cb) {
useEffect(() => {
socket.on(eventName, cb)
return function useSocketCleanup() {
socket.off(eventName, cb)
}
}, [eventName, cb])
return socket
}
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"express": "^4.15.2", "express": "^4.15.2",
"isomorphic-unfetch": "^2.0.0", "isomorphic-unfetch": "^3.0.0",
"next": "latest", "next": "latest",
"react": "^16.7.0", "react": "^16.7.0",
"react-dom": "^16.7.0", "react-dom": "^16.7.0",
......
import { Component } from 'react' import { useState } from 'react'
import Link from 'next/link' import Link from 'next/link'
import fetch from 'isomorphic-unfetch' import fetch from 'isomorphic-unfetch'
import useSocket from '../hooks/useSocket'
class ChatTwo extends Component { export default function ChatOne(props) {
// fetch old messages data from the server const [field, setField] = useState('')
static async getInitialProps({ req }) { const [newMessage, setNewMessage] = useState(0)
const response = await fetch('http://localhost:3000/messages/chat2') const [messages, setMessages] = useState(props.messages || [])
const messages = await response.json()
return { messages }
}
static defaultProps = { const socket = useSocket('message.chat2', message => {
messages: [], setMessages(messages => [...messages, message])
} })
// init state with the prefetched messages useSocket('message.chat1', () => {
state = { setNewMessage(newMessage => newMessage + 1)
field: '', })
newMessage: 0,
messages: this.props.messages,
subscribe: false,
subscribed: false,
}
subscribe = () => { const handleSubmit = event => {
if (this.state.subscribe && !this.state.subscribed) {
// connect to WS server and listen event
this.props.socket.on('message.chat2', this.handleMessage)
this.props.socket.on('message.chat1', this.handleOtherMessage)
this.setState({ subscribed: true })
}
}
componentDidMount() {
this.subscribe()
}
componentDidUpdate() {
this.subscribe()
}
static getDerivedStateFromProps(props, state) {
if (props.socket && !state.subscribe) return { subscribe: true }
return null
}
// close socket connection
componentWillUnmount() {
this.props.socket.off('message.chat1', this.handleOtherMessage)
this.props.socket.off('message.chat2', this.handleMessage)
}
// add messages from server to the state
handleMessage = message => {
this.setState(state => ({ messages: state.messages.concat(message) }))
}
handleOtherMessage = () => {
this.setState(prevState => ({ newMessage: prevState.newMessage + 1 }))
}
handleChange = event => {
this.setState({ field: event.target.value })
}
// send messages to server and add them to the state
handleSubmit = event => {
event.preventDefault() event.preventDefault()
// create message object // create message object
const message = { const message = {
id: new Date().getTime(), id: new Date().getTime(),
value: this.state.field, value: field,
} }
// send object to WS server // send object to WS server
this.props.socket.emit('message.chat2', message) socket.emit('message.chat2', message)
setField('')
// add it to state and clean current input value setMessages(messages => [...messages, message])
this.setState(state => ({
field: '',
messages: state.messages.concat(message),
}))
} }
render() {
return ( return (
<main> <main>
<div> <div>
<Link href={'/'}> <Link href="/">
<a>{`Chat One ${ <a>
this.state.newMessage > 0 {`Chat One${
? `( ${this.state.newMessage} new message )` newMessage > 0 ? ` ( ${newMessage} new message )` : ''
: '' }`}
}`}</a> </a>
</Link> </Link>
<br /> <br />
<Link href={'/clone'}> <Link href="/clone">
<a>{'Chat Two'}</a> <a>Chat Two</a>
</Link> </Link>
<ul> <ul>
{this.state.messages.map(message => ( {messages.map(message => (
<li key={message.id}>{message.value}</li> <li key={message.id}>{message.value}</li>
))} ))}
</ul> </ul>
<form onSubmit={e => this.handleSubmit(e)}> <form onSubmit={handleSubmit}>
<input <input
onChange={this.handleChange} onChange={e => setField(e.target.value)}
type="text" type="text"
placeholder="Hello world!" placeholder="Hello world!"
value={this.state.field} value={field}
/> />
<button>Send</button> <button>Send</button>
</form> </form>
</div> </div>
</main> </main>
) )
}
} }
export default ChatTwo ChatOne.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/messages/chat2')
const messages = await response.json()
return { messages }
}
import { Component } from 'react' import { useState } from 'react'
import Link from 'next/link' import Link from 'next/link'
import fetch from 'isomorphic-unfetch' import fetch from 'isomorphic-unfetch'
import useSocket from '../hooks/useSocket'
class ChatOne extends Component { export default function ChatOne(props) {
// fetch old messages data from the server const [field, setField] = useState('')
static async getInitialProps({ req }) { const [newMessage, setNewMessage] = useState(0)
const response = await fetch('http://localhost:3000/messages/chat1') const [messages, setMessages] = useState(props.messages || [])
const messages = await response.json()
return { messages }
}
static defaultProps = { const socket = useSocket('message.chat1', message => {
messages: [], setMessages(messages => [...messages, message])
} })
// init state with the prefetched messages useSocket('message.chat2', () => {
state = { setNewMessage(newMessage => newMessage + 1)
field: '', })
newMessage: 0,
messages: this.props.messages,
subscribe: false,
subscribed: false,
}
subscribe = () => { const handleSubmit = event => {
if (this.state.subscribe && !this.state.subscribed) {
// connect to WS server and listen event
this.props.socket.on('message.chat1', this.handleMessage)
this.props.socket.on('message.chat2', this.handleOtherMessage)
this.setState({ subscribed: true })
}
}
componentDidMount() {
this.subscribe()
}
componentDidUpdate() {
this.subscribe()
}
static getDerivedStateFromProps(props, state) {
if (props.socket && !state.subscribe) return { subscribe: true }
return null
}
// close socket connection
componentWillUnmount() {
this.props.socket.off('message.chat1', this.handleMessage)
this.props.socket.off('message.chat2', this.handleOtherMessage)
}
// add messages from server to the state
handleMessage = message => {
this.setState(state => ({ messages: state.messages.concat(message) }))
}
handleOtherMessage = () => {
this.setState(prevState => ({ newMessage: prevState.newMessage + 1 }))
}
handleChange = event => {
this.setState({ field: event.target.value })
}
// send messages to server and add them to the state
handleSubmit = event => {
event.preventDefault() event.preventDefault()
// create message object // create message object
const message = { const message = {
id: new Date().getTime(), id: new Date().getTime(),
value: this.state.field, value: field,
} }
// send object to WS server // send object to WS server
this.props.socket.emit('message.chat1', message) socket.emit('message.chat1', message)
setField('')
// add it to state and clean current input value setMessages(messages => [...messages, message])
this.setState(state => ({
field: '',
messages: state.messages.concat(message),
}))
} }
render() {
return ( return (
<main> <main>
<div> <div>
<Link href={'/'}> <Link href="/">
<a>{'Chat One'}</a> <a>{'Chat One'}</a>
</Link> </Link>
<br /> <br />
<Link href={'/clone'}> <Link href="/clone">
<a>{`Chat Two ${ <a>
this.state.newMessage > 0 {`Chat Two${
? `( ${this.state.newMessage} new message )` newMessage > 0 ? ` ( ${newMessage} new message )` : ''
: '' }`}
}`}</a> </a>
</Link> </Link>
<ul> <ul>
{this.state.messages.map(message => ( {messages.map(message => (
<li key={message.id}>{message.value}</li> <li key={message.id}>{message.value}</li>
))} ))}
</ul> </ul>
<form onSubmit={e => this.handleSubmit(e)}> <form onSubmit={e => handleSubmit(e)}>
<input <input
onChange={this.handleChange} onChange={e => setField(e.target.value)}
type="text" type="text"
placeholder="Hello world!" placeholder="Hello world!"
value={this.state.field} value={field}
/> />
<button>Send</button> <button>Send</button>
</form> </form>
</div> </div>
</main> </main>
) )
}
} }
export default ChatOne ChatOne.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/messages/chat1')
const messages = await response.json()
return { messages }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment