0

I made a question earlier which is mostly confused nonsense (Mongoose, array in object)

Now I Think I have narrowed it down to the following:

I have a list of drivers which has an Array of cars:

var driverSchema = new mongoose.Schema({

  driver: String,
  age: String,
  cars: [{ type: Schema.Types.ObjectId, ref: 'Car' }]

});
module.exports = mongoose.model('Driver', driverSchema);

A driver-object can be selected to ChoosenDriver like so:

 this.setState({choosenDriver:driver})

The problem is that the object Changes when selected. It changes from this:

drivers: array[3]
 ->0: {}
 ->1: {}
      _v: 0
      _id: "4242594395935934"
      name: "Roger"
      cars: Array[1]

to this:

choosenDriver: {..}
 _v:0
 _id: "235345353453"
 name: "Roger"
 cars: 
    ->_proto_ :{..} 
    0: "4242594395935934", 
   _id: undefined 

cars is no longer an Array when the driver is selected. Anyone run into something similar maybe?

Update: I pass the list of drivers to a Child Component like this:

<DriversList drivers={this.props.drivers}

In DriversList i select a driver like this: (render-func should be enough to show you)

 handleDriverClick: function(i) {

  this.props.setChoosenDriver(this.props.drivers[i])
 },

render: function(){
    var self  = this;
    var drivers = this.props.drivers.map(function(driver,i){
     return <li key={driver._id} onClick={self.handleDriverClick.bind(null, i)}> {driver.name} </li>;
   });

And in the Parent :

 setChoosenDriver: function(driver) {
      this.props.setChoosenDriver(driver)

      },

And finally in the GrandParent i set the state:

 setChoosenDriver: function(driver) {

        this.setState({choosenDriver:driver})

      },

Update:

     getInitialState: function() {
      return {    
         drivers:[]
      };
      },

componentWillMount: function(){

    var self = this;
      request
         .get(Driversurl)
         .end(function(err, res){
          self.setState({drivers: res.body});
         });

    },

Its an Array of drivers wtih objects like:

{"_id":"5607b0747eb3eefc225aed61","name":"Moore","__v":0,"cars":["5607b0747eb3eefc225aed61","5607b07a7eb3eefc225aed62","5606bf4b0e76916c1d1668b4","5607b07a7eb3eefc225aed62"]}
Community
  • 1
  • 1
RogerDore
  • 93
  • 1
  • 7

1 Answers1

0

don't execute your request in componentWillMount this is really wrong , execute it in componentDidMount, see this for more details : bind(this) not working on ajax success function

Also I would parse you request result when you receive it, your problem may come from here

self.setState({drivers:JSON.parse(res.body)});
Community
  • 1
  • 1
François Richard
  • 6,817
  • 10
  • 43
  • 78