[Solved] Uncaught TypeError: Cannot read property 'data' of null
Problem:
In a React component if you want to fetch value asynchronously and make it available to your component in props. But it returns null instead of an empty object. And throw an error like,
Uncaught TypeError: Cannot read property 'data' of null
Solution:
The TypeError: Cannot read properties of null (reading 'data') occurs when your first render, your data with that id isn't mounted to the DOM yet. Because of that, the data returns null.
You should use React's state. If you're using a class component, you can use this.state to have a property the value of which tells whether the data is set or not. The data needs a change handler, For example, if you use a checkbox something like this
<input type="checkbox" id="myCheck" onChange={(state) => this.setState({isChecked: !state.isChecked})} />
Then want to conditionally use the isChecked state you can use it in getClassBadge
return this.state.isChecked ? "badge m-2 bg-warning" : "badge m-2 bg-primnary"
Thank you for reading the article. Hope it will solve your problem. If you have any query you can comment below.