Data is passing from parent to child accordingly hence its showing inside render function but I am unable to use that to a async function which I need to run before the render.
If you see the data.title
and data.link
all showa under the render function but for some reason they are showing this error:
×
TypeError: Cannot read property 'link' of null
What can I alternatively do?
export default class Highlight extends Component {
state = {
htmlString: ''
}
fetchActivity = () => {
axios({
method: 'post',
url: 'api/singleactivity',
data: { activityLink: "http://play.fisher-price.com" + this.props.data.link }
})
.then((res) => {
this.setState({
htmlString: res.data
})
})
.catch((err) => {
console.log('There was an error fetching data', err);
})
}
componentDidMount() {
this.fetchActivity()
}
render() {
if (this.props.visibility.highlight) {
return (
<div>
<section className="card bg-info"
aria-label="Book Detail">
<div className="bg-secondary">
<h2>{this.props.data.title}</h2>
<h2>{this.props.data.link}</h2>
<h2>{this.props.data.imageLink}</h2>
</div>
<br />
<div className="row" dangerouslySetInnerHTML={{ __html: this.state.htmlString }}>
</div>
<br />
<div className="bg-warning">
{!this.props.visibility.favorites ?
<button onClick={() => this.addToFavorites()}> Favorite</button> :
<button onClick={() => this.removeFromFavorites()}> Remove</button>}
</div>
</section>
<br />
</div>
)
} else {
return null;
}
}
Well, mixing fetch calls and view code or using dangerouslySetInnerHTML apart, your prop this.props.data
does not always hold a value and this is the direct source of your issue.
So surely you're using your component this way <Highlight data={stuff} ... />
you can change it to something like {stuff ? <Highlight data={stuff} ... /> : null}
so the component won't be created in the first place if the input data is not ready yet.