Skip to content

Instantly share code, notes, and snippets.

@mjackson
Created May 22, 2019 16:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjackson/bde653c85c3aa39b9ab27b4affcf2373 to your computer and use it in GitHub Desktop.
Save mjackson/bde653c85c3aa39b9ab27b4affcf2373 to your computer and use it in GitHub Desktop.
// We want to subscribe to some data. Here are 2 ways to do the SAME thing.
// 1. setup some state
// 2. subscribing to a uid, set posts when they come in
// 3. unsubscribing when the component unmounts
// 4. when the uid changes:
// - unsubscribing from prev uid
// - re-subscribing to the new uid
// Here's a render prop:
class Posts extends React.Component {
constructor(props) {
super(props)
this.state = { posts: null }
}
subscribe() {
this.unsubscribe = subscribeToPosts(this.props.uid, posts => {
this.setState({ posts })
})
}
componentDidMount() {
this.subscribe()
}
componentDidUpdate(prevProps) {
if (prevProps.uid !== this.props.uid) {
this.unsubscribe()
this.subscribe()
}
}
componentWillUnmount() {
this.unsubscribe()
}
render() {
return this.props.children(this.state.posts)
}
}
// Use it like this:
// <Posts uid={...}>
// {posts => (
// // render your list
// )}
// </Posts>
// This hook does the same stuff!
function usePosts(uid) {
const [posts, setPosts] = useState(null)
useEffect(() => subscribeToPosts(uid, setPosts), [uid])
return posts
}
// Use it like this:
// const posts = usePosts(uid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment