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
console.log(Array.isArray(this.state.rooms))? Because seems thatthis.state.roomsisObjectnotArrayObject {amenities: "Kitchen, ...}is the result ofconsole.log(this.state.rooms)? Then here's the problem,this.state.roomsis an Object (representing a single room I guess), not an Array. If you only expect a single room from the API then eitherthis.setState({rooms: [ data ]});(replace the current array) orthis.setState({rooms: this.state.rooms.puch(data)});(to append the room), or fix your API to return arrays./api/v1/rentals? But we can't answer on this question because we have not seen your backend API