-
-
Save wbobeirne/07b794d330673ededefee4802aa2696b to your computer and use it in GitHub Desktop.
This file contains 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
interface State { | |
posts: Post[]; | |
isConnecting: boolean; | |
error: Error | null; | |
} | |
// Starting state, can be used for "resetting" as well | |
const INITIAL_STATE: State = { | |
posts: [], | |
isConnecting: true, | |
error: null, | |
}; | |
export default class App extends React.Component<State> { | |
state: State = { ...INITIAL_STATE }; | |
// Connect websocket immediately | |
componentDidMount() { | |
this.connect(); | |
} | |
// Reset our state, connect websocket, and update state on new data or error | |
private connect = () => { | |
this.setState({ ...INITIAL_STATE }); | |
const socket = api.getPostsWebSocket(); | |
// Mark isConnecting false once connected | |
socket.addEventListener('open', () => { | |
this.setState({ isConnecting: false }); | |
}); | |
// Add new posts when they're sent | |
socket.addEventListener('message', ev => { | |
try { | |
const msg = JSON.parse(ev.data.toString()); | |
if (msg && msg.type === 'post') { | |
// Add new post, sort them by most recent | |
const posts = [...this.state.posts, msg.data] | |
.sort((a, b) => b.time - a.time); | |
this.setState({ posts }); | |
} | |
} catch(err) { | |
console.error(err); | |
} | |
}); | |
// Handle closes and errors | |
socket.addEventListener('close', () => { | |
this.setState({ error: new Error('Connection to server closed unexpectedly.') }); | |
}); | |
socket.addEventListener('error', (ev) => { | |
this.setState({ error: new Error('There was an error, see your console for more information.') }); | |
console.error(ev); | |
}); | |
}; | |
render() { | |
/* ... */ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment