Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create single-prop HOCs for Meteor
// 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
You can’t perform that action at this time.