For some reason my map function is not returning anything in the render.
Basically I have a function that does a scrape with cheerio and then it stores the results in an array, then sets the state with it. When I check the react tools it shows that the state is updated with the array as expected. However, when the map function does not render anything and is blank on the screen.
I used very similar code in my last project but it's not working here, I feel I'm missing something simple but can't figure it out.
Here's the code:
import React, { Component } from 'react';
import { Trender } from '../Trender/trender';
import request from 'request';
import cheerio from 'cheerio';
export class Reddit extends Component {
constructor(props) {
super(props);
this.state = {
reddit: [],
ready: 0
}
this.getRedditTrending = this.getRedditTrending.bind(this);
}
getRedditTrending = () => {
var results = [];
request('http://old.reddit.com/r/leagueoflegends', function(error, response, html) {
var $ = cheerio.load(html);
console.log('hi')
$("p.title").each(function(i, element) {
var link = 'https://reddit.com' + $(element).children().attr("href");
var title = $(element).children().text();
console.log('hit')
results.push({
link: link,
title: title
})
})
})
this.setState({
reddit: results,
ready: 1,
})
}
componentDidMount(){
this.getRedditTrending()
}
render(){
if (this.state.ready == 1) {
return (
<div>
{<div>{this.state.reddit.map((i, item) => (<div>
<div key={i}>{item.title} </div>
</div>))}</div>}
</div>
)
}
else { return <div>hi</div>}
}
}
It's not giving me an error either. The map function doesn't show anything, but when I replace it with random text like "hello", that does get shown. Appreciate any advice, thanks.