All Projects → nicolaslopezj → react-meteor-data

nicolaslopezj / react-meteor-data

Licence: other
Fetch Meteor data in React using decorators

Programming Languages

javascript
184084 projects - #8 most used programming language

React Meteor Data

Fetch Meteor data in React using decorators

Medium Post

Installing

Install the package

meteor add orionsoft:react-meteor-data

Install the babel decorator

npm install --save-dev babel-plugin-transform-decorators-legacy

Create or update the .babelrc file in the root of your app

{
  "plugins": [
    "babel-plugin-transform-decorators-legacy"
  ]
}

### Example with publication

import React from 'react'
import {Meteor} from 'meteor/meteor'
import {withData} from 'meteor/orionsoft:react-meteor-data'
import MyCollection from './my-collection'

/**
 * Prop will be checked also in the container
 */
const propTypes = {
  itemId: React.PropTypes.string.isRequired,
  isLoading: React.PropTypes.bool,
  item: React.PropTypes.string
}

@withData(({itemId}) => {
  const handler = Meteor.subscribe('myPublication', itemId)
  const isLoading = !handler.ready()
  const item = MyCollection.findOne(itemId)
  return {isLoading, item}
})
export default class Component extends React.Component {

  render () {
    if (this.props.isLoading) return <span/>
    return (
      <div>
        {this.props.item.name}
      </div>
    )
  }

}

Component.propTypes = propTypes

### Example with method

import React from 'react'
import {Meteor} from 'meteor/meteor'
import {withMethodData} from 'meteor/orionsoft:react-meteor-data'

/**
 * Prop will be checked also in the container
 */
const propTypes = {
  itemId: React.PropTypes.string.isRequired,
  isLoading: React.PropTypes.bool,
  item: React.PropTypes.string
}

@withMethodData(({itemId}, ready) => {
  Meteor.call('getItem', itemId, ready)
})
export default class Component extends React.Component {

  render () {
    if (this.props.isLoading) return <span/>
    return (
      <div>
        {this.props.item.name}
      </div>
    )
  }

}

Component.propTypes = propTypes

// On the server
Meteor.methods({
  'getItem': function (itemId) {
    const item = Items.findOne(itemId)
    return {item} // objects returned in the method will be passed as props
  }
})
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].