I have react App.js page from where i am calling Django Rest API and i am getting response as an array now this array i have nested components and i want that nested component to be listed in my code.

If i can showcase single record given by single person name when i try to do with more than one i am getting following error. Warning: Each child in an array or iterator should have a unique "key" prop.

Now if i change API URL as below https://e2isaop.rokuapp.com/api/perns/1

I can able to view data in HTML but when it comes to all persons it fails.

I am sorry i am new react not sure how to iterate over sub array of result. Kindly guide me here for best practice for this.

Here is API Response in JSON

{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "uri": "/api/Persons/1",
            "PersonId": 1,
            "PersonName": "Nirav Joshi",
            "Person_Image": "https://ja.amazonaws.com/media/persons/None/51e1257926f3cb184089c41fa54b8f8e1b65a98f1e35d39e55f2b6b335e83cf4.jpg",
            "Person_sex": "M",
            "Person_BDate": "2019-04-19",
            "Person_CDate": "2019-04-23"
        },
        {
            "uri": "/api/Persons/2",
            "PersonId": 2,
            "PersonName": "New Joshi",
            "Person_Image": "https://ja.amazonaws.com/media/persons/None/cc08baaad2ccc918bc87e14cac01032bade23a0733b4e313088d61ee78d77d64.jpg",
            "Person_sex": "F",
            "Person_BDate": "2011-11-21",
            "Person_CDate": "2019-04-27"
        },

    ]
}

Here is react App.js code.

import React from "react";
import ReactDOM from "react-dom";
import Persons from "./Persons";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      persons: []
    };
  }

  componentDidMount() {
    fetch("https://e2isen.okuapp.com/api/psons/")
      .then(response => response.json())
      .then(data => {
        let apipersons;
        if (data.isNull) {
          apipersons = [];
        } else {
          apipersons = [data];
          console.log(apipersons);
        }

        this.setState({ persons: apipersons });
      });
  }

  render() {
    return (
      <div>
        <h1>Welcome to PersonAPI</h1>
        <div>
          {this.state.persons.map(pers => {
            return (
              <Persons
                PersonName={pers.PersonName}
                key={pers.PersonId}
                Person_Image={pers.Person_Image}
                Person_BDate={pers.Person_BDate}
                Person_sex={pers.Person_sex}
              />
            );
          })}
        </div>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));

It should give me result for Four person with their details PersonName PersonImage PersonBdate PersonSex

1 Answers

2
Loïck Munoz On Best Solutions

You should do :

// apipersons = [data];
apipersons = data.results