My fetch gives me the following JSON:
“{“name”:”John”,”age”:26,”city”:”London”}”
However when i try to render it on my page like this:
JavaScript
x
54
54
1
import React from 'react';
2
import './App.css';
3
import * as microsoftTeams from "@microsoft/teams-js";
4
5
class Tab extends React.Component {
6
constructor(props){
7
super(props)
8
this.state = {
9
context: {}
10
}
11
}
12
13
componentDidMount() {
14
fetch("http://localhost/openims/json.php?function=getDocuments&input=")
15
.then(res => res.json())
16
.then(
17
(result) => {
18
this.setState({
19
isLoaded: true,
20
files: result.files
21
});
22
},
23
(error) => {
24
this.setState({
25
isLoaded: true,
26
error
27
});
28
}
29
)
30
}
31
32
render() {
33
const { error, isLoaded, files } = this.state;
34
if (error) {
35
return <div>Error: {error.message}</div>;
36
} else if (!isLoaded) {
37
return <div>Loading</div>;
38
} else {
39
return (
40
<ul>
41
{files.map(file => (
42
<li key={file.id}>
43
{file.name} {file.age} {file.city}
44
</li>
45
))}
46
</ul>
47
);
48
}
49
50
}
51
52
}
53
export default Tab;
54
I get a TypeError: Cannot read property ‘map’ of undefined
How can i fix this?
Thanks in advance!
Advertisement
Answer
Given that the API response is {"name":"John","age":26,"city":"London"}
then I suggest the following:
Save the entire response result into state. Use a
catch
block to catch any errors and set any error state, and use afinally
block to set the loading state (more DRY).JavaScript114141componentDidMount() {
2fetch("http://localhost/openims/json.php?function=getDocuments&input=")
3.then(res => res.json())
4.then((result) => {
5this.setState({ result });
6})
7.catch((error) => {
8this.setState({ error });
9})
10.finally(() => {
11this.setState({ isLoaded: true })
12});
13}
14
Render from state, no array, just the state fields.
JavaScript118181render() {
2const { error, isLoaded, name, age, city } = this.state;
3
4if (error) {
5return <div>Error: {error.message}</div>;
6} else if (!isLoaded) {
7return <div>Loading</div>;
8} else {
9return (
10<ul>
11<li>
12{name} {age} {city}
13</li>
14</ul>
15);
16}
17}
18