Skip to content

Instantly share code, notes, and snippets.

@CaptainN
Last active January 31, 2020 18:15
Show Gist options
  • Save CaptainN/4d1d39693c32f6f1878c48e4252e3585 to your computer and use it in GitHub Desktop.
Save CaptainN/4d1d39693c32f6f1878c48e4252e3585 to your computer and use it in GitHub Desktop.
Meteor Robust Prefab Hooks
import { useTracker } from 'meteor/react-meteor-data'
// Create a reusable hook
const useAccount = () => useTracker(() => {
const user = Meteor.user()
const userId = Meteor.userId()
return {
user,
userId,
isLoggedIn: !!userId
}
}, [])
// And another
const usePage = (pageId) => useTracker(() => {
// The publication must also be secure
const subscription = Meteor.subscribe('page', pageId)
const page = Pages.findOne({ _id: pageId })
return {
page,
isLoading: !subscription.ready()
}
}, [pageId])
// Here we see the real benefit of hooks vs. containers
const MyProtectedPage = (pageId) => {
const { isLoggedIn, user } = useAccount()
const { isLoading, page } = usePage(pageId)
if (!isLoggedIn) {
return <div>
<Link to="/register">Create an Account</Link>
<Link to="/login">Log in</Link>
</div>
}
return <div>
<h1>{page.title}</h1>
<p>{page.content}</p>
<a href="#" onClick={(e) => { e.preventDefault(); Meteor.logout(); }}>Log out ({user.username})</a>
</div>)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment