Reputation: 11
Intro:
I'm newbie in meteor, I have read the documentation and questions here about this issue but the doubt still persist. My main problem is that I cant load data of my MongoDb in client side (what methods to use to load data).
Example:
I have a project that has the following folder structure: image
In my collections (People.js) I have this:
import { Mongo } from 'meteor/mongo';
export const People = new Mongo.Collection('people');
In the server folder ( main.js ). PS: I can't change this file.
import { People } from '../collections/people';
Meteor.startup(() => {
const TEST_DATA = [
{
something: 'This is a simple example',
}, ... ]
TEST_DATA.forEach(test => People.insert(test));
}
In UI folder (app.jsx)
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import { Meteor } from 'meteor/meteor';
import {People} from '../collections/people';
export class App extends Component {
render() {
return (
<div>
<h3>Teste </h3>
{ console.log(this.users) }
{ console.log(People.find({}).fetch()) }
{ console.log(Meteor.subscribe('people')) }
</div>
);
}
}
export default withTracker(() => {
return {
users: People.find({}).fetch(),
};
})(App);
cliente folder (main.jsx):
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import { App } from '../ui/App';
Meteor.startup(() => {
render(<App />, document.getElementById('app'));
});
Debug:
I inspected the database and it's populated. The first console.log show undefined , the second an array of length:0, the third an object {stop: ƒ, ready: ƒ, subscriptionId: "mJQHdGxka4xTCX7FZ"}
(I think it's returning this because I'm not using publish () on the server to populate the database)
What method should I use to obtain this data?
Upvotes: 1
Views: 381
Reputation: 21354
Change app.jsx
to
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import { Meteor } from 'meteor/meteor';
import {People} from '../collections/people';
export class App extends Component {
render() {
console.log(this.props.users)
return (
<div>
<h3>Teste </h3>
{ this.props.users.map((user) => { return (<div>user.something</div>) }) }
</div>
);
}
}
export default withTracker(() => {
Meteor.subscribe('people');
return {
users: People.find({}).fetch(),
};
})(App);
I've modified the code a little further in the direction that I would assume you'd want it to go. The core change is it use this.props.users
. That's where the properties in React components can be found, and where they are places by the function returned by withTracker
.
This all assumes that you are still using autopublish
(as meteor does in new projects until you remove it). If you have already removed that package, then you need to add
Meteor.publish('people', () => {
return People.find();
});
in your server code.
Upvotes: 1