Last active
May 16, 2018 14:18
-
-
Save rdickert/2762d9f3e5c1ae53100939a90eed4a86 to your computer and use it in GitHub Desktop.
Create single-prop HOCs for Meteor
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
// Creating Meteor HOCs | |
import { Meteor } from 'meteor/meteor'; | |
import { createContainer } from 'meteor/react-meteor-data'; | |
import React from 'react'; | |
import { compose } from 'recompose'; | |
// Assuming we have a Meteor collection here... | |
import TodosCollection from '../api/TodosCollection'; | |
// This curries the createContainer function so that you call it with | |
// meteorHoc(fn)(component); | |
// Any Tracker reactive data source will cause it to rerender and pass | |
// its properites to the child component. | |
const meteorHoc = fn => | |
component => createContainer(fn, component); | |
// Now we can make an HOC that provides a single reactive prop to our components | |
const isLoggedIn = meteorHoc(() => ({ isLoggedIn: !!Meteor.userId() })); | |
// It's also great for queries and methods | |
const myTodos = meteorHoc(() => ({ myTodos: TodosCollection.find({ userId: Meteor.userId() }).fetch() })); | |
// If you name your HOCs after the propnames, it's easy to trace where | |
// things came from. These HOCs would be imported from another file | |
// if we had a larger app, giving us nice separation of concerns. | |
const App = ({ isLoggedIn, myTodos }) => { | |
return isLoggedIn && | |
<ul> | |
{myTodos.map((todo) => <li>{todo.goal}</li>)} | |
</ul>; | |
} | |
// By defining them separately, we can add or remove them independently. | |
// You can easily combine these with HOCs from Apollo (GraphQL), react-komposer, | |
// Redux, or whatever you like. | |
// The compose function gives a clear indication of how we are assembling our component. | |
export default compose(isLoggedIn, myTodos)(App); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment