I'm trying to get images from Reddit based on my search parameters. I'm fetching fine and am able to retrieve my data, but the url I receive in data.preview.images[0].source.url
(Reddit really buries it in there) are all prefixed with https://external-preview.redd.it/
. When I click on the link in the response, I get a forbidden message.
I've seen videos where people are able to retrieve the images, but they are able to do so via a prefixed i-reddit link or what have you. I dug around for a bit in the JSON response but couldn't find any compatible links.
Any ideas?
Edit:
Here's my code with the fetching:
state = {
redditData: []
}
componentDidMount(){
fetch(`https://www.reddit.com/search.json?q=animal_crossing`)
.then(response => response.json())
.then(redditData => this.setState({redditData: redditData.data.children.slice(5, 10)}))
}
itsCardTime = () => {
return this.state.redditData.map(rd => <RedditCard key={rd.id} data={rd.data}/>)
}
render(){
return(
<div className="homecontent">
<div className="homeimage">
<h1 >cute image</h1>
</div>
<div className="redditdata">
{this.itsCardTime()}
</div>
</div>
)
}
}
And here's my code that should be rendering the image:
render(){
console.log(this.props.data)
return(
<div className="redditcard">
<h5>
{this.props.data.title}
{/* {this.props.data.preview ? console.log(this.props.data.preview.images[0].resolutions[0].url) : null } */}
{/* {this.props.data.preview ? <img src={this.props.data.preview.images[0].source.url}/> : null} */}
</h5>
<p>{this.props.data.subreddit_name_prefixed}</p>
</div>
)}
}
My responses are coming back in JSON format and I'm able to console log them.
I figured it out, and am leaving the solution here as I expect others will run into this issue when fetching from Reddit after their upgrade. Basically, you have to escape the encoded URL that they are sending you. I did so with the following method:
getUrl = (imgUrl) => {
let encoded = imgUrl.replace('amp;s', 's')
let doubleEncoded = encoded.replace('amp;', '')
let tripleEncoded = doubleEncoded.replace('amp;', '')
return tripleEncoded
}
though I'm sure there are other and better ways to get around it. I'll leave the link to my Reddit post in which a user directed me to this solution in case anyone wants to look into it and come up with something better for themselves.
https://www.reddit.com/r/redditdev/comments/ihgw5j/cant_get_the_images_to_populate_from_my_fetch/