Home > database >  Component not changing after state change (componentDidMount fetch) - React
Component not changing after state change (componentDidMount fetch) - React

Time:01-31

I'm making an news app following a tutorial I'm fetching data from newapi my code looks same as tutorial but my component does not change after I update the state (this.state.articles) I'm using setState function i tried console logging the state it looks fine after the state is updated render methods runs but it does not change anything what could be worng

my code/component

import React, { Component } from 'react'
import NewsItem from './NewsItem'

export default class News extends Component {
    articles = [
        {
            "source": {
                "id": "espn-cric-info",
                "name": "ESPN Cric Info"
            },
            "author": null,
            "title": "PCB hands Umar Akmal three-year ban from all cricket | ESPNcricinfo.com",
            "description": "Penalty after the batsman pleaded guilty to not reporting corrupt approaches | ESPNcricinfo.com",
            "url": "http://www.espncricinfo.com/story/_/id/29103103/pcb-hands-umar-akmal-three-year-ban-all-cricket",
            "urlToImage": "https://a4.espncdn.com/combiner/i?img=/i/cricket/cricinfo/1099495_800x450.jpg",
            "publishedAt": "2020-04-27T11:41:47Z",
            "content": "Umar Akmal's troubled cricket career has hit its biggest roadblock yet, with the PCB handing him a ban from all representative cricket for three years after he pleaded guilty of failing to report det… [ 1506 chars]"
        },
        {
            "source": {
                "id": "espn-cric-info",
                "name": "ESPN Cric Info"
            },
            "author": null,
            "title": "What we learned from watching the 1992 World Cup final in full again | ESPNcricinfo.com",
            "description": "Wides, lbw calls, swing - plenty of things were different in white-ball cricket back then | ESPNcricinfo.com",
            "url": "http://www.espncricinfo.com/story/_/id/28970907/learned-watching-1992-world-cup-final-full-again",
            "urlToImage": "https://a4.espncdn.com/combiner/i?img=/i/cricket/cricinfo/1219926_1296x729.jpg",
            "publishedAt": "2020-03-30T15:26:05Z",
            "content": "Last week, we at ESPNcricinfo did something we have been thinking of doing for eight years now: pretend-live ball-by-ball commentary for a classic cricket match. We knew the result, yes, but we tried… [ 6823 chars]"
        }
    ]

    constructor() {
        super();
        this.state = {
            articles: this.articles,
            loading: false
        }
    }

    async componentDidMount() {
        const URL = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=4c61131ff6c544999ed1b8585d1cac6b"
        let data = await fetch(URL);
        let parsedData = await data.json()
        this.setState({
            articles: parsedData.articles
        })
        console.log(this.state.articles)
    }
    render() {
        console.log("render")
        return (
            <div>
                <div className="container">
                    <h2 className='my-4 mx-4'> NewsMonkey - Top Headlines </h2>
                    <div className="row">
                        {this.articles.map((elem) => {
                            return <div className="col-md-4" key={elem.url}>
                                <NewsItem title={elem.title?elem.title.slice(42):""} desc={elem.description?elem.description.slice(0, 88): ""} url={elem.url} imgURL={elem.urlToImage} />
                            </div>
                        })}
                    </div>
                </div>
            </div>
        )
    }
}

CodePudding user response:

this.articles and this.state.articles are not the same.

You have a static property this.articles that you are using in the render logic - this.articles.map(.... Your fetch is updating state (like it should be).

Update your render to read from this.state.articles and it should work.

CodePudding user response:

Hi @Curious Your code is correct

you just need to pay attention when making the map

you are using this.articles which is a fixed (mock) list

you need to call map in this.state.articles because this is the state you change in didMount

  • Related