Reputation: 1584
I am having an error with the map function. I dont know what might be the reason but it says this.state.rooms.map is not a function. I have fetched the data from api and pushed into an empty list . The list is successfully updated with the contents but could not apply map function on it.
Here's my code
import React from 'react';
import ReactDOM from 'react-dom';
export default class RoomList extends React.Component{
constructor(props){
super(props);
this.state = { rooms: [] }
}
componentDidMount(){
console.log('componentDidMount');
this.loadRoomFromServer();
}
loadRoomFromServer(){
$.ajax({
url:'/api/v1/rental/',
dataType:'json',
success: (data) => {
this.setState({rooms: data});
},
error: (xhr, status, err) => {
console.error(url, status, err.toString());
}
});
}
render(){
console.log('rooms',this.state.rooms);
let listOfRoom = this.state.rooms.map((room)=>{
return(
<Room key={room.id} name={room.listingName} price={room.price} number={room.room} />
)
});
return(
<div className="container-fluid">
<div className="row">
{ listOfRoom }
</div>
</div>
)
}
}
class Room extends React.Component{
render(){
return(
<div className="col-md-4">
<h2>{this.props.name}</h2>
<p>{this.props.price}</p>
<p>{this.props.number}</p>
</div>
)
}
}
what i get on the console is
room []
componentDidMount
room Object {amenities: "Kitchen, Cable", city: "city", email: "[email protected]", listingName: "tushant", ownerName: "tushant"…}
Uncaught TypeError: this.state.rooms.map is not a function
Upvotes: 0
Views: 219
Reputation: 2852
as @sfletche mentioned map
function for arrays only.
change your success
callback to
success: (data) => {
this.setState({rooms: data.objects});
},
error: (xhr, status, err) => {
console.error(url, status, err.toString());
}
});
Upvotes: 2
Reputation: 49764
There is no map
function for objects, only arrays.
Your second output of rooms
shows the answer
room Object {amenities: "Kitchen, Cable", city: "city", email:
"[email protected]", listingName: "tushant", ownerName: "tushant"…}
rooms
is now an object and the map
function is specific to arrays.
Upvotes: 2