Adi Pîslaru
Adi Pîslaru

Reputation: 149

Use variable outside of map function with react

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);

Upvotes: 0

Views: 1688

Answers (1)

Kevin Amiranoff
Kevin Amiranoff

Reputation: 14543

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>
    );
  }
}

Upvotes: 1

Related Questions