0

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.

1 Answer 1

2

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>
        ))
    )
}

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, thank you a lot! It works! Now I can read the code to understand the difference and why mine wasn' working ;)
1. In ReactJS don't use Array.prototype.push(). 2. You create let cards = [] and push data to it from the promise. Then pass cards to this.setState({ cards }); But Promise will be fulfilled after this.setState({ cards }); So you pass empty array to state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.