0

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

5
  • could you add to your question result of console.log(Array.isArray(this.state.rooms)) ? Because seems that this.state.rooms is Object not Array Commented Feb 26, 2016 at 11:51
  • 1
    So the Object {amenities: "Kitchen, ...} is the result of console.log(this.state.rooms)? Then here's the problem, this.state.rooms is an Object (representing a single room I guess), not an Array. If you only expect a single room from the API then either this.setState({rooms: [ data ]}); (replace the current array) or this.setState({rooms: this.state.rooms.puch(data)}); (to append the room), or fix your API to return arrays. Commented Feb 26, 2016 at 11:53
  • yes object is the result of this.state.rooms . I want to fetch all the room from the API but i could only fetch one room. I did this.setState({rooms:[data]}). What should be done inorder to fetch all the room from an api? Commented Feb 26, 2016 at 12:08
  • 1
    @Tushant maybe URL for ajax should looks like this /api/v1/rentals ? But we can't answer on this question because we have not seen your backend API Commented Feb 26, 2016 at 12:11
  • my bad i forgot to change that . I was tweaking my code. Thanks. Commented Feb 26, 2016 at 12:13

2 Answers 2

2

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());
  }
});
Sign up to request clarification or add additional context in comments.

9 Comments

This way i could fetch only 1 room from an api as i want to fetch all the room from an api.
the issue is from the api (backend) not from frontend you need to make sure you are sending array of rooms, if you can post your API response
yes now i get such imgur.com/VZEkPMZ . I am getting all the room now. I forgot to change my url.
but nothing is rendered in my template.
if you can post your response here, and console.log in success callback
|
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.