Armin Masoomi
Armin Masoomi

Reputation: 135

Can't display data from Mongo in meteor using react

Can anyone help me with this issue please, I'm running React on Meteor and i have this Component to add some data to Mongo using TrackerReact, But i cant display them in another populate these data in another component, I'm abale to console.log data after the page load, therefore i think maybe the page load before the Mongo data loads, any suggestion please help,Thank you:

here is Adminadd.jsx where i save on mongo:

import React from 'react';
import TrackerReact from 'meteor/ultimatejs:tracker-react'

Gifts= new Mongo.Collection("gifts");

export default class AdminAdd extends TrackerReact(React.Component){
addGift(event){
    event.preventDefault();

    giftName=this.refs.giftname.value.trim();
    giftCity=this.refs.giftcity.value.trim();
    giftActive=this.refs.giftactive.checked;

    Gifts.insert({
        name: giftName,
        city: giftCity,
      active: giftActive,
    });

    this.refs.giftname.value="";
    this.refs.giftcity.value="";
    this.refs.giftactive.checked=false;
}

render(){..RenderStuff..}

here is where i want to load them:

import React from 'react';
import Gift from './components/Gift.jsx'
export default class Main extends React.Component{
allgifts(){
    return Gifts.find().fetch();
}
render(){
    console.log(allgifts());
    return(
        <div className="row">
        {this.allgifts().map((gift)=>{
            return
                <Gift gift={gift} key={gift._id}/>})}
        </div>
    )}}

and the Gift Component:

import React from 'react';
export default class Gift extends React.Component{
render(){
    return(
        <div>
            <div>
                <div>{this.props.gift.name}</div>
                <div>{this.props.gift.city}</div>
                <div>{this.props.gift.active}</div>
            </div>
        </div>
    )}}

and this is console log, at first return empty object, then when i Gifts.find().fetch() it manual it works after that:

[]
Gifts.find().fetch()
Object, Object, Object, Object, Object, Object, Object, Object]

Upvotes: 4

Views: 455

Answers (2)

Waiski
Waiski

Reputation: 9680

As koolaang said, the template may be rendered for the first time before the Gifts collection is loaded. The real issue is however that it's not reactively re-rendered when the collection is loaded. This is because you haven't wrapped your Main component in TrackerReact. So you need to fix it like this:

export default class Main extends TrackerReact(React.Component) { ... }

Now the component should be re-rendered once the collection loads. You can check for subscription readiness if you want to implement a loading-state, but it's not required.

Upvotes: 3

koolaang
koolaang

Reputation: 417

it is because, it takes time for the data from backend to your frontend. if you are using publish/subscribe you should use handle.ready to wait for the data to get to the frontend.

Upvotes: 1

Related Questions