Created
May 22, 2019 16:21
-
-
Save mjackson/bde653c85c3aa39b9ab27b4affcf2373 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
// 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