提交 442fbfaa 编写于 作者: D Dave Brudner 提交者: Joe Haddad

Update with-socket.io example (#9583)

* Using custom hook instead of `_app.js` to interface with
`socket.io-client`
上级 9bf48687
......@@ -33,4 +33,4 @@ yarn dev
## 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 @@
"version": "1.0.0",
"dependencies": {
"express": "^4.15.2",
"isomorphic-unfetch": "^2.0.0",
"isomorphic-unfetch": "^3.0.0",
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0",
......
import { Component } from 'react'
import { useState } from 'react'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
import useSocket from '../hooks/useSocket'
class ChatTwo extends Component {
// fetch old messages data from the server
static async getInitialProps({ req }) {
const response = await fetch('http://localhost:3000/messages/chat2')
const messages = await response.json()
return { messages }
}
static defaultProps = {
messages: [],
}
// init state with the prefetched messages
state = {
field: '',
newMessage: 0,
messages: this.props.messages,
subscribe: false,
subscribed: false,
}
subscribe = () => {
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()
}
export default function ChatOne(props) {
const [field, setField] = useState('')
const [newMessage, setNewMessage] = useState(0)
const [messages, setMessages] = useState(props.messages || [])
componentDidUpdate() {
this.subscribe()
}
const socket = useSocket('message.chat2', message => {
setMessages(messages => [...messages, message])
})
static getDerivedStateFromProps(props, state) {
if (props.socket && !state.subscribe) return { subscribe: true }
return null
}
useSocket('message.chat1', () => {
setNewMessage(newMessage => newMessage + 1)
})
// 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 => {
const handleSubmit = event => {
event.preventDefault()
// create message object
const message = {
id: new Date().getTime(),
value: this.state.field,
value: field,
}
// send object to WS server
this.props.socket.emit('message.chat2', message)
// add it to state and clean current input value
this.setState(state => ({
field: '',
messages: state.messages.concat(message),
}))
socket.emit('message.chat2', message)
setField('')
setMessages(messages => [...messages, message])
}
render() {
return (
<main>
<div>
<Link href={'/'}>
<a>{`Chat One ${
this.state.newMessage > 0
? `( ${this.state.newMessage} new message )`
: ''
}`}</a>
</Link>
<br />
<Link href={'/clone'}>
<a>{'Chat Two'}</a>
</Link>
<ul>
{this.state.messages.map(message => (
<li key={message.id}>{message.value}</li>
))}
</ul>
<form onSubmit={e => this.handleSubmit(e)}>
<input
onChange={this.handleChange}
type="text"
placeholder="Hello world!"
value={this.state.field}
/>
<button>Send</button>
</form>
</div>
</main>
)
}
return (
<main>
<div>
<Link href="/">
<a>
{`Chat One${
newMessage > 0 ? ` ( ${newMessage} new message )` : ''
}`}
</a>
</Link>
<br />
<Link href="/clone">
<a>Chat Two</a>
</Link>
<ul>
{messages.map(message => (
<li key={message.id}>{message.value}</li>
))}
</ul>
<form onSubmit={handleSubmit}>
<input
onChange={e => setField(e.target.value)}
type="text"
placeholder="Hello world!"
value={field}
/>
<button>Send</button>
</form>
</div>
</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 fetch from 'isomorphic-unfetch'
import useSocket from '../hooks/useSocket'
class ChatOne extends Component {
// fetch old messages data from the server
static async getInitialProps({ req }) {
const response = await fetch('http://localhost:3000/messages/chat1')
const messages = await response.json()
return { messages }
}
static defaultProps = {
messages: [],
}
// init state with the prefetched messages
state = {
field: '',
newMessage: 0,
messages: this.props.messages,
subscribe: false,
subscribed: false,
}
subscribe = () => {
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()
}
export default function ChatOne(props) {
const [field, setField] = useState('')
const [newMessage, setNewMessage] = useState(0)
const [messages, setMessages] = useState(props.messages || [])
componentDidUpdate() {
this.subscribe()
}
const socket = useSocket('message.chat1', message => {
setMessages(messages => [...messages, message])
})
static getDerivedStateFromProps(props, state) {
if (props.socket && !state.subscribe) return { subscribe: true }
return null
}
useSocket('message.chat2', () => {
setNewMessage(newMessage => newMessage + 1)
})
// 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 => {
const handleSubmit = event => {
event.preventDefault()
// create message object
const message = {
id: new Date().getTime(),
value: this.state.field,
value: field,
}
// send object to WS server
this.props.socket.emit('message.chat1', message)
// add it to state and clean current input value
this.setState(state => ({
field: '',
messages: state.messages.concat(message),
}))
socket.emit('message.chat1', message)
setField('')
setMessages(messages => [...messages, message])
}
render() {
return (
<main>
<div>
<Link href={'/'}>
<a>{'Chat One'}</a>
</Link>
<br />
<Link href={'/clone'}>
<a>{`Chat Two ${
this.state.newMessage > 0
? `( ${this.state.newMessage} new message )`
: ''
}`}</a>
</Link>
<ul>
{this.state.messages.map(message => (
<li key={message.id}>{message.value}</li>
))}
</ul>
<form onSubmit={e => this.handleSubmit(e)}>
<input
onChange={this.handleChange}
type="text"
placeholder="Hello world!"
value={this.state.field}
/>
<button>Send</button>
</form>
</div>
</main>
)
}
return (
<main>
<div>
<Link href="/">
<a>{'Chat One'}</a>
</Link>
<br />
<Link href="/clone">
<a>
{`Chat Two${
newMessage > 0 ? ` ( ${newMessage} new message )` : ''
}`}
</a>
</Link>
<ul>
{messages.map(message => (
<li key={message.id}>{message.value}</li>
))}
</ul>
<form onSubmit={e => handleSubmit(e)}>
<input
onChange={e => setField(e.target.value)}
type="text"
placeholder="Hello world!"
value={field}
/>
<button>Send</button>
</form>
</div>
</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% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册