Thibault
Thibault

Reputation: 137

React fetching and displaying data issue

I'm new to react, and trying to practice I'm facing an issue. I want to fetch data from Hacker News, and display the content.

Well, the fetch part is OK, I get the urls I want with the content I want. But when I try to display it nothing happens. If I log the content, I can see it, but I'm not able to display it in HTML.

Anyone has an idea about it?

Here's the code

setUrls () {

        // Define API base URL
        let baseUrl = "https://hacker-news.firebaseio.com/v0/item/";

        // IDs of stories
        const ids = [22694891,22693792,22696252,22697212,22695174,22660888,22689301,22695264];

        // Empty Array for content
        const cards = []

        for (let i = 0; i < ids.length; i++){
            fetch(baseUrl + ids[i] + ".json")
            .then(response => response.json())
            .then((data) => {
                cards.push(data);  
            })
        }
        this.setState({
            cards: cards
        })
    }

    componentDidMount () {
        this.setUrls();
    }

    render() {
        let cards = this.state.cards;
        console.log(cards)

        return (
            cards.map(card => {
                return (
                    <div>{card.id}</div>
                )
            })
        )
    }

In render(), when I log the state I can see it, but then the HTML is empty.

Upvotes: 0

Views: 55

Answers (1)

Kirill Skomarovskiy
Kirill Skomarovskiy

Reputation: 1575

I refactor your code. Try it.

setUrls () {
    // Define API base URL
    let baseUrl = "https://hacker-news.firebaseio.com/v0/item/";

    // IDs of stories
    const ids = [
      22694891,
      22693792,
      22696252,
      22697212,
      22695174,
      22660888,
      22689301,
      22695264,
    ];
    
    ids.forEach((id) => {
      fetch(`${baseUrl}${id}.json`)
        .then(response => response.json())
        .then((data) => {
          this.setState(({ cards }) => ({
            cards: [ ...cards, data ]
          }));
        })
        .catch(({ message }) => {
          console.error(message);
        });
    });
}

componentDidMount () {
    this.setUrls();
}

render() {
    const { cards } = this.state;

    return (
        cards.map(card => (
          <div>{card.id}</div>
        ))
    )
}

Upvotes: 2

Related Questions