I am trying to understand, i know when i console.log(pictures) i get the end result
and when i "console.log(JSON.stringify(pictures))" i get the current one at that moment.
why does in that moment when it logs the second option, the array is empty and in the end it got a value,
how can i force the synchronization of the value and this.state
the problem is that when i am sending in the end:
ImageList pics={this.state.picturesArr} />
it is being sent empty
let pictures = [];
let urls =[];
let titles=[];
let nextpage ='';
let pageback='';
class App extends Component {
constructor(props) {
super(props);
this.state = {
picturesArr: [],
urlArr: [],
titleArr:[],
nextPage:'',
prevuisPage:''
};
this.loadSubreddit = this.loadSubreddit.bind(this);
}
loadSubreddit(subre) {
reddit.hot(subre).limit(5).fetch(function(res) {
console.log(res);
nextpage = res.data.after.toString();
// pageback = res.data.before.valueOf();
for (let i = 0; i < res.data.children.length; i++){
pictures.push(res.data.children[i].data.url);
urls.push(res.data.children[i].data.permalink);
titles.push(res.data.children[i].data.title);
}
});
this.setState({
picturesArr: pictures,
urlArr: urls,
titleArr: titles,
nextPage: nextpage,
prevuisPage: pageback
}, () => {
console.log(this.state)
});
console.log(pictures);
console.log(JSON.stringify(pictures));
}
componentWillMount() {
console.log('comp is mounting');
this.loadSubreddit('cats');
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<Col sm={8} md={10} smOffset={2} mdOffset={1} >
<ImageList pics={this.state.picturesArr} />
</Col>
</div>
);
}
}
export default App;