I'm working on a node js and react app. I'm trying to fetch the following dataset from my back-end:
[{"name":"nameonehere#1"},{"name":"nameonehere#2"},
{"name":"nameonehere#3"},{"nameonehere#4"},...,{"name":"nameonehere#xxx"}]
Here is my app.js:
class App extends Component {
state = {
data: null,
loading: true,
error: false
};
componentDidMount() {
fetch('http://localhost:5000/getData')
.then(res => {
if (!res.ok) {
throw res;
}
return res.json()
}).then(data => {
// setState triggers re-render
this.setState({loading: false, data});
}).catch(err => {
console.error(err);
this.setState({loading: false, error: true});
});
}
render() {
return (
<div className="App">
...
<div>
{this.state.loading ? <p>Loading...</p>
: this.state.error ? <p>Error during fetch!</p>
: (
<ul>
this.state.data.map(data =>
<div key={data.id}>data: {data.name}</div>)
</ul>
)}
</div>
</div>
);
}
}
and I have the following error 'data' is not defined
the error is line 80 which is this line of code:
<div key={data.id}>data: {data.name}</div>)
I tried a few things but nothing is working. I'm a bit lost between JS and JSX.
What is the issue?
'data' is not defineddoesn't make sense then, but that could be a typo to SO offcourse.datalooks like when returned from your API?