React Hooks for Meteor.
npm install react-meteor-hooks``javascript
import React from 'react'
import { useCurrentUser } from 'react-meteor-hooks'
const UserWidget = () => {
const currentUser = useCurrentUser()
return(
{ currentUser.userName }
:You are not logged in.
}`
and can return reactive data.
`javascript
import React from 'react'
import { useTracker } from 'react-meteor-hooks'const UserBooks = (sortBy) => {
const data = useTracker(() => {
const userProfile = Meteor.user().profile
const userBooks = Books.find({ _owner: Meteor.userId() }, { sort: { [sortBy]: -1 }})
return { userProfile, userBooks }
}, [sortBy])
// pass [sortBy] as second arg - so that this function will be rerun if sortBy changes
const books = data.userBooks.map(Book)
// ...
}
`$3
Subscribes to a publication and returns a reactive "loading" var.
`javascript
import React from 'react'
import { useSubscription } from 'react-meteor-hooks'const UserBooks = (sortBy, showLimit) => {
const loading = useSubscription('user_books', showLimit)
// subscription will be rerun if showLimit changes
if (loading) {
// ...
}
// ...
}
`$3
Returns { isLoading, data, error, call } object to work with meteor methods.
Full example including useEffect at https://codesandbox.io/s/kj9zqqyrr
`javascript
import React from 'react'
import { useMethod } from 'react-meteor-hooks'const UserBooks = () => {
const { isLoading, data, error, call } = useMethod('add_book', { transform: result => result.updatedAt = new Date() })
if (isLoading) return 'Adding book...'
if (error) return
Error: ${err.message}
return (
onClick={async () => {
await call('Moby Dick')
console.log('Meteor call completed')
}}
>
Add
{data && (
New book added at {data.updatedAt.toLocalString()}. ID: {data.id}
)}
)
}export default UserBooks
`$3
Fetches a MongoQuery and returns the result.
`javascript
import React from 'react'
import { useMongoFetch, useSubscription } from 'react-meteor-hooks'const UserBooks = (sortBy, showLimit) => {
const loading = useSubscription('user_books', showLimit)
if (loading) {
// ...
} else {
const allBooks = useMongoFetch(Books.find({}, { sort: { [sortBy] : -1 }}), [sortBy])
const books = allBooks.map(/ ... /)
// ...
}
}
`$3
Returns the current logged in User or null.
`javascript
import React from 'react'
import { useCurrentUser, useSubscription } from 'react-meteor-hooks'const UserBooks = (sortBy, showLimit) => {
const user = useCurrentUser()
if (user) {
const loading = useSubscription('user_books', showLimit)
if (loading) {
// ...
} else {
// ...
}
}
}
`$3
Returns value of a Session var.
`javascript
import React from 'react'
import { useSession } from 'react-meteor-hooks'Session.set('currentPage', 1)
const UserBooks = (sortBy, showLimit) => {
const page = useSession('currentPage')
// ...
}
``