Im trying to make a const like this const feedURL = this.state.podcasts[0].feedUrl
But the state is not updated with the fetch I do above where I set the state of podcasts, so i get TypeError: Cannot read property 'feedUrl' of undefined
, that I understand.
But HOW should i get this to work? Anyone who can point me in the right direction..
This is my component:
import React, { Component } from 'react'
import Feed from 'feed-to-json-promise'
import sanitizeHtml from 'sanitize-html'
export default class Podcast extends Component {
state = {
podcasts: [],
episodes: [],
loading: true,
}
componentDidMount () {
const podId = this.props.match.params.podId
fetch(`https://itunes.apple.com/lookup?id=${podId}`)
.then(response => response.json())
.then(podcasts => this.setState({
podcasts: podcasts.results,
loading: false,
}))
const feed = new Feed()
const feedURL = this.state.podcasts[0].feedUrl
feed.load(feedURL)
.then(feedInfo => this.setState({
episodes: feedInfo.items
}))
}
render() {
const { podcasts, episodes, loading } = this.state
const { podId } = this.props.match.params
if (loading === true) return null
const { collectionName, artworkUrl600, primaryGenreName, feedUrl } = podcasts.find((podcast) => podcast.collectionId === Number(podId))
return (
<div>
<img src={artworkUrl600} alt={collectionName} style={{width: '300px'}} />
<h2>{collectionName} ({podId})</h2>
<p>{primaryGenreName}</p>
<p><a href={feedUrl} target='_blank'>RSS Feed URL</a></p>
<ul>
{episodes.map((episode, i) => {
const { title, description } = episode;
return (
<li key={title.slice(0, 3)}>
<h2>{title}</h2>
<p>{sanitizeHtml(description, {allowedTags: [], allowedAttributes: []})}</p>
</li>
)
})}
</ul>
</div>
)
}
}