Skip to content

Instantly share code, notes, and snippets.

@CaptainN
Last active January 1, 2021 21:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CaptainN/4cf649aa0a92d1ac206773495995ed47 to your computer and use it in GitHub Desktop.
Save CaptainN/4cf649aa0a92d1ac206773495995ed47 to your computer and use it in GitHub Desktop.
Meteor Hooks Kitchen Sink
import { useTracker } from 'meteor/react-meteor-data'
// Create a reusable subscribe hook
const usePageSubscription = (pageId) => useTracker(() => {
const subscription = Meteor.subscribe('page', pageId)
return !subscription.ready()
}, [pageId])
// Separate page hook
const usePage = (pageId) => useTracker(() => {
const page = Pages.findOne({ _id: pageId })
return page
}, [pageId])
// A hook for account
const useAccount = () => useTracker(() => {
const user = Meteor.user()
const userId = Meteor.userId()
return {
user,
userId,
isLoggedIn: !!userId
}
}, [])
const MyProtectedPage = (pageId) => {
const isLoading = usePageSubscription(pageId)
const page = usePage(pageId)
const { isLoggedIn, user } = useAccount()
if (!isLoggedIn) {
return <Redirect to="/login" />
} else if (isLoading) {
<Loading />
}
return <div>
<h1>{page.title}</h1>
<p>{page.content}</p>
<a href="#" onClick={(e) => { e.preventDefault(); Meteor.logout(); }}>Log out ({user.username})</a>
</div>)
}
// We can easily make old style HOCs out of the hooks
const withUser = (Component) => (props) => {
const accountProps = useAccount()
return <Component {...props} {...accountProps} />
}
const withPage = (Component) => (props) => (
const pageProps = usePage(props.pageId)
return <Component {...props} {...pageProps} />
)
// Or, we can make a Context
const AccountContext = createContext('account')
export const AccountProvider = (props) => (
<AccountContext.Provider value={useAccount()}>
{props.children}
</AccountContext.Provider>
)
export const AccountConsumer = AccountContext.Consumer
// This requires AccountProvider to be included in the app tree.
export const useAccountContext = () => useContext(AccountContext)
// ...and then make a HoC
export const withAccountContext = (Component) => (props) => {
const account = useAccountContext()
return <Component {...props} {...account} />
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment