0

I want to call an API using react Js,where JSON data is not in an array

when am running this code am getting an error:this.props.result.map is not a function.

The API which am calling is not an array its just JSON object

  here is  my code:

   var App = React.createClass({
  //setting up initial state
  getInitialState:function(){
    return{
        data:[]
    };
  },

  getDataFromServer:function(URL){
    $.ajax({
        type:"GET",
        dataType:"json",
        url:URL,
        headers:{
      'Content-Type':'application/json',
                },
        success: function(response) {
            this.showResult(response);
        }.bind(this),
        error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
        }.bind(this)
    });
   },

 showResult: function(response) {

        this.setState({
            data: JSON.parse(response)
        });
},

  var Result = React.createClass({
render:function(){
    var result = this.props.result.map(function(result,index){
        return <ResultItem key={index} user={ result } />
        });
    return(<div className="row">
           <div className="col-md-12">
               <table className="table table-bordered">
                   <thead>
                       <tr>
                           <th className="col-md-4">Id</th>
                           <th >Name</th>
                           <th>Independent</th>
                           <th>Description</th>
                           <th>uuid</th>
                      </tr>
                   </thead>
                   <tbody>
                       {result}
                   </tbody>
               </table>
           </div>
       </div>)
          }
  });
  var ResultItem = React.createClass({
render:function(){
    var camper = this.props.user;
    return(
                        <tr >
                            <td>{camper.id}</td>
                            <td>{camper.name}</td>
                            <td>{camper.independent}</td>
                            <td>{camper.description}</td>
                            <td>{camper.uuid}</td>
                        </tr>

                );
          }
       });
Swathi.r
  • 1
  • 1

1 Answers1

0

I'm going to make an assumption about the structure of the JSON you get from your API. Let's say it's an object that looks something like this:

{
  1234: {
    uuid: 1234,
    id: 'abcd',
    etc: 'etc'
  },
  5678: {
    uuid: 5678,
    etc: 'etc'
  }
}

To use Array.prototype.map you'll need to convert it to an array. There are some great ways to do that in this answer, for example:

var mappableResult = Object.keys(data).map(function (key) {return data[key]});

If this doesn't do the trick, please post an example of what your response data looks like.

Community
  • 1
  • 1
Andy_D
  • 4,112
  • 27
  • 19