While trying to fetch values in a class component I am getting the below error. Here I am trying to get data from an API Gateway. The goal is to pick each attribute from JSON response and display them in a frontend dynamic table.
Can someone please help me out in fixing it? Thanks
Error:
TypeError: Cannot read properties of undefined (reading 'map')
Code:
import React, {Component} from 'react'
import axios from '../../axios'
export default class users extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
getUsersData() {
axios
.post(`/`, { ParentId: 'ou-wmno-yeeol4ok' })
.then(res => {
const data = res.data;
const users = data.Accounts.map(u =>
<div>
<p>{u.Id}</p>
</div>
)
this.setState({
users
})
})
.catch((error) => {
console.log(error)
})
}
componentDidMount(){
this.getUsersData()
}
render() {
return (
<div>
{this.state.users}
</div>
)
}
}
JSON Data as API Response:
{
"Accounts": [
{
"Id": "2556",
"Arn": "arn:aws:organizations::2556:account/ooabc/2556",
"Email": "2556@aws.test.aws",
"Name": "test-account",
"Status": "SUSPENDED",
"JoinedMethod": "CREATED",
"JoinedTimestamp": "2021-07-13T14:58:23.197000+00:00"
},
],
"ResponseMetadata": {
"RequestId": "131462d1-47b2-4c19-aed0-8a30fb6859bd",
"HTTPStatusCode": 200,
"HTTPHeaders": {
"x-amzn-requestid": "131462d18a30fb5959bd",
"content-type": "application/x-amz-json-1.1",
"content-length": "3527",
"date": "Mon, 13 Sep 2021 15:42:52 GMT"
},
"RetryAttempts": 0
}
}
thanks, everyone- I think I figured it out by using JSON Parser.
getUsersData() {
axios
.post(`/`, { ParentId: 'ou-wmno-yeeol4ok' })
.then(res => {
const data = res.data
const valuesArray = JSON.parse(data)
console.log(valuesArray)
const users = valuesArray.Accounts.map(u =>
<tr key={u.Id}>
<td>{u.Name}</td>
<td>{u.Arn}</td>
<td>{u.Id}</td>
<td>{u.Email}</td>
<td>{u.JoinedMethod}</td>
<td>{u.JoinedTimestamp}</td>
<td>{u.Status}</td>
</tr>
)
this.setState({
users
})
})
.catch((error) => {
console.log(error)
})
}
usually fetching data is done using the "get" method and not with the "post" method