I am trying to fetch an array of JSON objects onto my react page. Now, the array I get is :
[{"_id":"5c4309fb643589310818165e","TableTime":"10:30- 11:00","TableType":"Pool Table 1","TableStatus":"Booked"},
{"_id":"5c430a3f2f788e322d2430d0","TableTime":"10:30- 11:00","TableType":"Pool Table 1","TableStatus":"Booked"}]
I first set it in a state variable result in componentDidMount() method.
In render method, when I do :
const { result } = this.state;
var slot = result;
console.log(slot);
I get the array as above. But when I do :
const { result } = this.state;
var slot = result;
console.log(slot[0].TableTime);
I get the error TypeError: Cannot read property 'TableTime' of undefined
I searched for it and tried this link and used JSON.parse(): Access elements of json in an Array in jquery
But then it gave me the error: SyntaxError: Unexpected token u in JSON at position 0
The relevant code is as follows :
class Timeslots extends Component {
constructor(props, context) {
super(props, context);
this.state = {
result: []
}
componentDidMount() {
this.getList();
}
getList = () => {
fetch("/purchase")
.then(res => res.json())
.then(result => this.setState({ result }))
}
render() {
const { result } = this.state;
var slot = result;
console.log(slot);
);
}
}
export default Timeslots;
I just want a way so that I can access the slot[0].TableTime and use it?
rendermethod runs even before the result has been fetched. At that time the value ofresultis just a blank array. That is why you are getting the error. All you have to do is to add aif(result[0])condition in render method which checks if value is there then only use that.