Last active
March 12, 2020 21:33
-
-
Save CaptainN/67b142c19481bedd08765c43cc4d2731 to your computer and use it in GitHub Desktop.
Meteor Robust useTracker
This file contains hidden or 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 { useTracker } from 'meteor/react-meteor-data' | |
// Hook, basic use, everything in one component | |
const MyProtectedPage = (pageId) => { | |
const { user, isLoggedIn, page } = useTracker(() => { | |
// The publication must also be secure | |
const subscription = Meteor.subscribe('page', pageId) | |
const page = Pages.findOne({ _id: pageId }) | |
const user = Meteor.user() | |
const userId = Meteor.userId() | |
const isLoggingIn = Meteor.loggingIn() | |
return { | |
page, | |
isLoading: !subscription.ready(), | |
user, | |
userId, | |
isLoggingIn, | |
isLoggedIn: !!userId | |
} | |
}, [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