0

I'm having a little problem with some vars.

My code is:

import React from 'react';
import mongoose from 'mongoose';
var sch = require('../models/schema');

export default class IndexPage extends React.Component {
  render() {

    sch.find(function(err,models){
       //???
    });

    return (
      <div className="home">
        Afiez ceva {models}
      </div>
    );

  }
}

How to achieve this? I ve tried all the posibilites. I want to be able to render someting like {models} or {models[0].whatever} .. Some tip please?

Reference for sch:

import mongoose from 'mongoose';

var schValue = new mongoose.Schema({
  asd: String
});

schValue.set( 'collection', 'ecommerce' );

module.exports = mongoose.model('sch', schValue);
8
  • 2
    Welcome to the wonderful world of async! You need to use callbacks or promises. Commented Feb 20, 2017 at 23:29
  • Should i use redux ? Commented Feb 20, 2017 at 23:32
  • 1
    You don't have to use redux. Although it is good to scale up you application. I am not sure what you are trying to do, but you need to use the state. You should make a function that uses setState() and use this.state inside your render function. Once the state updates, your component will rerender automatically : facebook.github.io/react/docs/state-and-lifecycle.html Commented Feb 20, 2017 at 23:37
  • 1
    Or maybe not. if you just want to render a list, you have to map over this list. and return this map inside the render function. Commented Feb 20, 2017 at 23:42
  • 1
    I ll try an answer. One minute Commented Feb 20, 2017 at 23:43

1 Answer 1

1

I have not tested it but is that something like this you need :

  export default class IndexPage extends React.Component {

  constructor() {
    super();

    this.state = {
      models: [],
    };
  }

  componentWillMount() {
    sch.find({}, (err, models) => {
      this.setState({ models });
    });
  }

  render() {
    return (
      <div className="home">
        {this.state.models.map(model => {
          return model;
        })}
      </div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

getModels not defined
Sorry again. I reedited. it should be this.getModels()
TypeError: sch.map is not a function
map works on array. Could you add to your question, what is sch ?
I am sorry. I misunderstood your question. I dont think my answer apply to your question
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.