i have a api with peoples i am tring to dispaly names of people
"peoples": [
{
"id": 2,
"mainModule": "bonding",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "hari",
"completed": false
},
{
"id": 4,
"name": "meenu",
"completed": false
}
]
"id": 1,
"mainModule": "bonding2",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "jisa",
"completed": false
},
{
"id": 4,
"name": "stepy",
"completed": false
}
]
},
]
This is my data in api
I am using axios to set a state called items
axios
.get(
"url",
config
)
.then((res) => {
console.log(res.data.peoples)//this works
console.log(res.data.peoples.persons);//here i am getting error
this.setState({ items: res.data.peoples.persons}); error
}
I am trying to pass persons so I can map person names in JSX
i have changed the code pls help
Welcome to StackOverflow! As you can see in your first snippet you have an array inside peoples so the correct way to access it would be:
res.data.peoples[0].persons
Hope this solves your problem. You can read more about it in MDN docs
edit:
If you would like to iterate over persons you can do this:
res.data.peoples.map(person => (
<div key={person.id}>{person.name}</div>
));
Remember you must pass a unique key prop to the component so React can create and mantain the list correctly. More info about it in the Docs.
res.data.peoples is an array so you should iterate over it. It doesn't have persons property, it has [0], [1] etc. Try to log res.data.peoples[0].persons
From the sample data you showed, peoples is an array. So to access persons, you should be able to access it using the following, for example if you want to access the first element of the array:
res.data.peoples[0].persons
Otherwise, if you want to access it as res.data.peoples.persons then you have to change your API output such that it is like so :
"peoples": {
"id": 2,
"mainModule": "bonding",
"description": "some random description 2",
"persons": [
{
"id": 3,
"name": "hari",
"completed": false
},
{
"id": 4,
"name": "meenu",
"completed": false
}
]
}