I’m building an app using react. I have a collection with 4 entries for test. I’m trying to fetch and dispay data from my collection, but I’m getting nothing displayed and the following consol errors:
Warning: Failed prop type: The prop `cars` is marked as required in `App`, but its value is `undefined`.
in App (created by Route)
in Route
in Switch
in Router (created by BrowserRouter)
in BrowserRouter
and
Uncaught TypeError: Cannot read property 'map' of undefined
at App.renderCars (App.jsx:41)
at App.render (App.jsx:70)
at printer.js:170
at measureLifeCyclePerf (printer.js:170)
Here is my code - client:
import { createContainer } from 'meteor/react-meteor-data';
//...some material ui imports
import PropTypes from 'prop-types';
import React, { Component } from 'react';
// Database - collection
import { Cars } from '../api/cars';
export class App extends Component {
constructor(props) {
super(props);
this.state = { cars: [] };
}
renderCars() {
return this.state.cars.map((car) => (
<CarsList key={car._id} car={car} />
));
}
render() {
return (
<MuiThemeProvider >
<div className = "container" >
<AppBar title = "CarDealer"
iconClassNameRight = "muidocs-icon-navigation-expand-more"
showMenuIconButton = { true } >
<AccountsWrapper />
</AppBar>
<List >
{ this.renderCars() }
</List>
<Divider />
</div>
</MuiThemeProvider>
);
}
}
App.propTypes = {
cars: PropTypes.array.isRequired,
};
export default createContainer(() => {
Meteor.subscribe('all-cars');
return {
cars: Cars.find({}, { sort: { createdAt: 1 } }).fetch(),
};
}, App);
import Avatar from 'material-ui/Avatar';
import { ListItem } from 'material-ui/List';
import React, { Component } from 'react';
export default class CarsList extends Component {
render() {
return (
<ListItem
primaryText={this.props.car.make}
leftAvatar={<Avatar src="cars.jpg"/>}
/>
);
}
}
In the server:
import { Meteor } from 'meteor/meteor';
import { Cars } from '../imports/api/cars';
Meteor.startup(() => {
Meteor.publish('all-cars', function() {
return Cars.find({});
});
});
Changing
renderCars() {
return this.props.cars.map((car) => (
<CarsList key={car._id} car={car} />
));
}
to
renderCars() {
return this.state.cars.map((car) => (
<CarsList key={car._id} car={car} />
));
}
Produces:
Warning: Failed prop type: The prop `cars` is marked as required in `App`, but its value is `undefined`.
in App (created by Route)
in Route
in Switch
in Router (created by BrowserRouter)
in BrowserRouter
Any help will be welcome.