CodeWithHarry / NewsMonkey-React

News App created using React and NewsAPI
268 stars 205 forks source link

TypeError: Cannot read properties of undefined (reading 'map') #6

Open Tausif-H6 opened 2 years ago

Tausif-H6 commented 2 years ago

312 |

313 |

314 | | ^ 315 | {this.state.articles.map((element)=>{ 316 | return

317 | <NewsItem title={element.title?element.title:""} description={element.description?element.description:""} imageUrl={element.urlToImage} newsUrl={element.url}/>

How to solve this error? Apka code bhi copy karliya phirbhi ye error a raha hain.

Sumon1510 commented 2 years ago

Map function applies only on string. const [articles, setArticles] = useState([ ])

Abhinav2212 commented 2 years ago

Hi ho699, Check your json object is it in [ ] ? . For example articles = [

      {
        "source": { "id": "bbc-sport", "name": "BBC Sport" },
        "author": "BBC Sport",
        "title": "T20 World Cup: Afghanistan win toss & bat first v Pakistan - clips, radio & text",
        "description": "Follow live text, TMS commentary and in-play clips as Pakistan play Afghanistan in the T20 World Cup at the Dubai International Cricket Stadium.",
        "url": "http://www.bbc.co.uk/sport/live/cricket/58257074",
        "urlToImage": "https:////m.files.bbci.co.uk/modules/bbc-morph-sport-seo-meta/1.21.1/images/bbc-sport-logo.png",
        "publishedAt": "2021-10-29T13:52:32.257218Z",
        "content": "Hello! This is fun - multitasking the finish between West Indies and Bangladesh with the build-up of this next game!\r\nI reckon we're in for some fun with this one, though. The entertaining Afghanista… [+29 chars]"
      },
      {
        "source": { "id": "engadget", "name": "Engadget" },
        "author": "https://www.engadget.com/about/editors/jon-fingas",
        "title": "Cricket brings 5G to all of its phone plans | Engadget",
        "description": "Cricket is enabling 5G for all its phone plans, and it's doing away with the 8Mbps cap as a result..",
        "url": "https://www.engadget.com/cricket-5g-no-speed-cap-all-plans-130022473.html",
        "urlToImage": "https://s.yimg.com/os/creatr-uploaded-images/2021-10/e4e5c400-3813-11ec-bfe7-50ec106670ff",
        "publishedAt": "2021-10-29T13:07:21.4585398Z",
        "content": "Cricket is no longer reserving 5G for its priciest service tier. As of today, 5G is enabled for all of the prepaid carrier's plans. As you might guess, the provider is also doing away with the modest… [+1216 chars]"
      },
      {
        "source": { "id": "abc-news-au", "name": "ABC News (AU)" },
        "author": "ABC News",
        "title": "Australian Test cricket great Ashley Mallett dies aged 76",
        "description": "Australian spin bowling great Ashley Mallett, who played 38 Tests and took 132 wickets at an average of 29.84, dies aged 76 after battling cancer.",
        "url": "http://www.abc.net.au/news/2021-10-29/australian-test-great-ashley-mallett-dies/100582246",
        "urlToImage": "https://live-production.wcms.abc-cdn.net.au/76373d099f09602411f7f5f04b378b4b?impolicy=wcms_crop_resize&cropH=2166&cropW=3850&xPos=0&yPos=559&width=862&height=485",
        "publishedAt": "2021-10-29T12:19:44Z",
        "content": "Australian spin bowling great Ashley Mallett has died at age 76 after battling cancer.\r\nMallett played 38 Tests from his debut against England in 1968 and took 132 wickets at an average of 29.84, als… [+329 chars]"
      },
      {
        "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=%2Fi%2Fcricket%2Fcricinfo%2F1099495_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=%2Fi%2Fcricket%2Fcricinfo%2F1219926_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]"
      }
    ]
or you can refer my full code 

import React, { Component } from 'react' // import PropTypes from 'prop-types' import NewsItem from './NewsItem'

export class News extends Component { articles = [

      {
        "source": { "id": "bbc-sport", "name": "BBC Sport" },
        "author": "BBC Sport",
        "title": "T20 World Cup: Afghanistan win toss & bat first v Pakistan - clips, radio & text",
        "description": "Follow live text, TMS commentary and in-play clips as Pakistan play Afghanistan in the T20 World Cup at the Dubai International Cricket Stadium.",
        "url": "http://www.bbc.co.uk/sport/live/cricket/58257074",
        "urlToImage": "https:////m.files.bbci.co.uk/modules/bbc-morph-sport-seo-meta/1.21.1/images/bbc-sport-logo.png",
        "publishedAt": "2021-10-29T13:52:32.257218Z",
        "content": "Hello! This is fun - multitasking the finish between West Indies and Bangladesh with the build-up of this next game!\r\nI reckon we're in for some fun with this one, though. The entertaining Afghanista… [+29 chars]"
      },
      {
        "source": { "id": "engadget", "name": "Engadget" },
        "author": "https://www.engadget.com/about/editors/jon-fingas",
        "title": "Cricket brings 5G to all of its phone plans | Engadget",
        "description": "Cricket is enabling 5G for all its phone plans, and it's doing away with the 8Mbps cap as a result..",
        "url": "https://www.engadget.com/cricket-5g-no-speed-cap-all-plans-130022473.html",
        "urlToImage": "https://s.yimg.com/os/creatr-uploaded-images/2021-10/e4e5c400-3813-11ec-bfe7-50ec106670ff",
        "publishedAt": "2021-10-29T13:07:21.4585398Z",
        "content": "Cricket is no longer reserving 5G for its priciest service tier. As of today, 5G is enabled for all of the prepaid carrier's plans. As you might guess, the provider is also doing away with the modest… [+1216 chars]"
      },
      {
        "source": { "id": "abc-news-au", "name": "ABC News (AU)" },
        "author": "ABC News",
        "title": "Australian Test cricket great Ashley Mallett dies aged 76",
        "description": "Australian spin bowling great Ashley Mallett, who played 38 Tests and took 132 wickets at an average of 29.84, dies aged 76 after battling cancer.",
        "url": "http://www.abc.net.au/news/2021-10-29/australian-test-great-ashley-mallett-dies/100582246",
        "urlToImage": "https://live-production.wcms.abc-cdn.net.au/76373d099f09602411f7f5f04b378b4b?impolicy=wcms_crop_resize&cropH=2166&cropW=3850&xPos=0&yPos=559&width=862&height=485",
        "publishedAt": "2021-10-29T12:19:44Z",
        "content": "Australian spin bowling great Ashley Mallett has died at age 76 after battling cancer.\r\nMallett played 38 Tests from his debut against England in 1968 and took 132 wickets at an average of 29.84, als… [+329 chars]"
      },
      {
        "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=%2Fi%2Fcricket%2Fcricinfo%2F1099495_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=%2Fi%2Fcricket%2Fcricinfo%2F1219926_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();
    console.log("Hi this is constructor");
    this.state = {
        articles  : this.articlesJSON,
        loading : false
    }
}

render() {
    return (
        <div className = "container my-3">
            <h2> News Headlines </h2>
           {this.articles.map((element)=>{console.log("this is map")})}
            <div className="row">
                <div className="col-md-4">
                    <NewsItem title = "mytitle" description = "mydesc" imageUrl = "https:////m.files.bbci.co.uk/modules/bbc-morph-sport-seo-meta/1.21.1/images/bbc-sport-logo.png"/>
                </div>

            </div>

        </div>
    )
}

}

export default News

BitCrecrz commented 2 years ago

@ho699 if you are facing any issue on this make sure you are using article as a state not as a props

i also facing the same problem but finally after 3 to 4 hours i resolved it

i am also sharing my code so you can check it

make sure you use your api key

import React, { Component } from "react"; import Newsitem from "./Newsitem"; // import PropTypes from 'prop-types'

export default class News extends Component { static defaultProps = { country: "in", pageSize: 10, category: "general", }; // static PropTypes = { // country: PropTypes.string, // pageSize: PropTypes.number, // category: PropTypes.string, // }

constructor() { super(); this.state = { articles: [], loading: false, page: 1, country: "in", category: "general", pageSize: 10 }; }

async componentDidMount() { let url = https://newsapi.org/v2/top-headlines?country=${this.props.country}&category=${this.props.category}&apiKey=0c6c101667df4819811538c161824dd&page=1&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ articles: parsedData.articles, totalResults: parsedData.totalResults, }); } hendlePrewClick = async () => { let url = https://newsapi.org/v2/top-headlines?country=${ this.props.country }&category=${ this.props.category }&apiKey=0c6c101667df4819811538c161824dd&page=${ this.state.page - 1 }&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ page: this.state.page - 1, articles: parsedData.articles, }); }; hendleNextClick = async () => { if ( this.props.page + 1 > Math.ceil(this.state.totalResults / this.props.pageSize) ) { } else { let url = https://newsapi.org/v2/top-headlines?country=${ this.props.country }&category=${ this.props.category }&apiKey=0c6c101667df4819811538c161824dd&page=${ this.state.page + 1 }&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ page: this.state.page + 1, articles: parsedData.articles, }); } }; render() { return (

Top-Headlines

{this.state.articles.map((elements) => { return (
); })}
);

} }

@CodeWithHarry thank you bro for this awsome course

Abhinav2212 commented 2 years ago

@ho699 if you are facing any issue on this make sure you are using article as a state not as a props

i also facing the same problem but finally after 3 to 4 hours i resolved it

i am also sharing my code so you can check it

make sure you use your api key

import React, { Component } from "react"; import Newsitem from "./Newsitem"; // import PropTypes from 'prop-types'

export default class News extends Component { static defaultProps = { country: "in", pageSize: 10, category: "general", }; // static PropTypes = { // country: PropTypes.string, // pageSize: PropTypes.number, // category: PropTypes.string, // }

constructor() { super(); this.state = { articles: [], loading: false, page: 1, country: "in", category: "general", pageSize: 10 }; }

async componentDidMount() { let url = https://newsapi.org/v2/top-headlines?country=${this.props.country}&category=${this.props.category}&apiKey=0c6c101667df4819811538c161824dd&page=1&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ articles: parsedData.articles, totalResults: parsedData.totalResults, }); } hendlePrewClick = async () => { let url = https://newsapi.org/v2/top-headlines?country=${ this.props.country }&category=${ this.props.category }&apiKey=0c6c101667df4819811538c161824dd&page=${ this.state.page - 1 }&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ page: this.state.page - 1, articles: parsedData.articles, }); }; hendleNextClick = async () => { if ( this.props.page + 1 > Math.ceil(this.state.totalResults / this.props.pageSize) ) { } else { let url = https://newsapi.org/v2/top-headlines?country=${ this.props.country }&category=${ this.props.category }&apiKey=0c6c101667df4819811538c161824dd&page=${ this.state.page + 1 }&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ page: this.state.page + 1, articles: parsedData.articles, }); } }; render() { return (

Top-Headlines

{this.state.articles.map((elements) => { return (

<Newsitem title={ elements.title ? elements.title : "Title Not Availible" } description={ elements.description ? elements.description : "Description Not Availible" } imageUrl={elements.urlToImage} NewsUrl={elements.url} />

); })}

<button disabled={this.state.page <= 1} type="button" className="btn btn-dark mx-2" onClick={this.hendlePrewClick}

←Prew

<button disabled={ this.state.page + 1 > Math.ceil(this.state.totalResults / this.props.pageSize) } type="button" className="btn btn-dark mx-2" onClick={this.hendleNextClick}

Next→

); } }

@CodeWithHarry thank you bro for this awsome course

Hi hide your API keys it is visible anyone can use it and can exhaust it.

BitCrecrz commented 2 years ago

@ho699 if you are facing any issue on this make sure you are using article as a state not as a props i also facing the same problem but finally after 3 to 4 hours i resolved it i am also sharing my code so you can check it make sure you use your api key import React, { Component } from "react"; import Newsitem from "./Newsitem"; // import PropTypes from 'prop-types' export default class News extends Component { static defaultProps = { country: "in", pageSize: 10, category: "general", }; // static PropTypes = { // country: PropTypes.string, // pageSize: PropTypes.number, // category: PropTypes.string, // } constructor() { super(); this.state = { articles: [], loading: false, page: 1, country: "in", category: "general", pageSize: 10 }; } async componentDidMount() { let url = https://newsapi.org/v2/top-headlines?country=${this.props.country}&category=${this.props.category}&apiKey=0c6c101667df4819811538c161824dd&page=1&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ articles: parsedData.articles, totalResults: parsedData.totalResults, }); } hendlePrewClick = async () => { let url = https://newsapi.org/v2/top-headlines?country=${ this.props.country }&category=${ this.props.category }&apiKey=0c6c101667df4819811538c161824dd&page=${ this.state.page - 1 }&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ page: this.state.page - 1, articles: parsedData.articles, }); }; hendleNextClick = async () => { if ( this.props.page + 1 > Math.ceil(this.state.totalResults / this.props.pageSize) ) { } else { let url = https://newsapi.org/v2/top-headlines?country=${ this.props.country }&category=${ this.props.category }&apiKey=0c6c101667df4819811538c161824dd&page=${ this.state.page + 1 }&pageSize=${this.props.pageSize}; let data = await fetch(url); let parsedData = await data.json(); console.log(parsedData); this.setState({ page: this.state.page + 1, articles: parsedData.articles, }); } }; render() { return (

Top-Headlines

{this.state.articles.map((elements) => { return ( <Newsitem title={ elements.title ? elements.title : "Title Not Availible" } description={ elements.description ? elements.description : "Description Not Availible" } imageUrl={elements.urlToImage} NewsUrl={elements.url} /> ); })} <button disabled={this.state.page <= 1} type="button" className="btn btn-dark mx-2" onClick={this.hendlePrewClick}

←Prew <button disabled={ this.state.page + 1 > Math.ceil(this.state.totalResults / this.props.pageSize) } type="button" className="btn btn-dark mx-2" onClick={this.hendleNextClick}

Next→ ); } } @CodeWithHarry thank you bro for this awsome course

Hi hide your API keys it is visible anyone can use it and can exhaust it.

i removed some part of my api key :P