Last active
January 28, 2020 20:49
-
-
Save CaptainN/fc963cc500eeddafdb2921a789e8b93a to your computer and use it in GitHub Desktop.
Meteor Containers
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
import { withTracker } from 'meteor/react-meteor-data' | |
// Create a reusable hook | |
const withAccount = withTracker((props) => { | |
const user = Meteor.user() | |
const userId = Meteor.userId() | |
return { | |
user, | |
userId, | |
isLoggedIn: !!userId | |
} | |
}) | |
// And another | |
const withPage = withTracker(({ pageId }) => { | |
// The publication must also be secure | |
const subscription = Meteor.subscribe('page', pageId) | |
const page = Pages.findOne({ _id: pageId }) | |
return { | |
page, | |
isLoading: !subscription.ready() | |
} | |
}) | |
// Here we see the real benefit of hooks vs. containers | |
const MyProtectedPage = ({ isLoggedIn, user, isLoading, page }) => { | |
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>) | |
} | |
const withAccount(withPage(MyProtectedPage)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment