Since we have basically rewritten the react-meteor-data
package to use React Hooks instead of the old HOC (while maintaining a backward compatible HOC built on the hook) I thought it would be nice to write a quick post on how to use it, and some its benefits. I have already a pretty good example for using account state that I’m using for my app which uses the hook (with deps, an optimization) in a Provider, and with a hook to grab the state from the context (behind the scenes), even with a compatible alternative for a HOC based on withTracker
that I had used all over the app previously. I think it would make a great way to introduce the useTracker
hook. I’ll probably write that up either way, but it would be cool if I could submit that for use on the blog.
Here is the example code (with little explanation - that’s to come!)
/* global Meteor */
import { createContext, useContext } from 'react'
import { useTracker } from 'meteor/react-meteor-data'
import { isSuperAdmin } from '/imports/utils/roles'
// This can be used directly, but is also used by the Context provider
export const useAccountDirect = () => useTracker(() => {
const user = Meteor.isServer ? null : Meteor.user()
const userId = Meteor.isServer ? null : Meteor.userId()
return {
user,
userId,
isLoggedIn: !!userId,
isSuperAdmin: isSuperAdmin(userId)
}
}, [])
const AccountContext = createContext('account')
export const AccountProvider = (props) => (
<AccountContext.Provider value={useAccountDirect()}>
{props.children}
</AccountContext.Provider>
)
export const AccountConsumer = AccountContext.Consumer
// This requires AccountProvider to be included in the app tree.
export const useAccount = () => useContext(AccountContext)
// Provides a backward compatible HOC to replace
// the old `withTracker` version.
export const withUser = (Component) => (props) => {
const account = useAccount()
return <Component {...props} {...account} />
}
Anyway, where would I submit?