I'm trying to fetch the contents of a static JSON file and display it in react.js. I'm basing my code on the examples given Here The code compiles, but when I open the page in a browser, I get this error message:
TypeError: Cannot read property 'data' of null
Here's my component:
import React, { Component } from 'react';
class UserList extends Component {
async getData(){
const res = await fetch('/static/users.json');
const data = await res.json();
console.log("Got Data : " + data.length);
return this.setState(
{data:data}
);
}
componentDidMount()
{
this.getData();
}
render(){
return (
<ul>{this.state.data.map(item => <li>{item.title}</li>)} </ul>
)
}
}
export default UserList;
getData
is an asynchronous function, as well as setState
. This creates a race condition between the time your component mounts, to the time it renders. Therefore you need to null check.
import React, { Component } from 'react';
class UserList extends Component {
async getData(){
const res = await fetch('/static/users.json');
const data = res.json();
console.log("Got Data : " + data.length);
return this.setState(
{data:data}
);
}
componentDidMount()
{
this.getData();
}
render(){
return (
<ul>{this.state && this.state.data && this.state.data.map(item => <li>{item.title}</li>)} </ul>
)
}
}
export default UserList;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments