Home > OS >  this.state.articles is undefined in React js
this.state.articles is undefined in React js

Time:12-14

I am creating a news app for my project and what i am basically doing is fetching the arrays of news articles from the API and then storing it in a articles array in my local memory and then I am using the map method on that array and thus rendering the articles on my web page but now I'm getting this error:

image of the error

I looked at some similar question I think what I am having a problem with the scope of the constructor. EDIT: I was wrong at the setstate part but i was just trying it out but the original code is this:

this.state = {
  articles: this.articles
}

the above code is the original code in the place of setstate that was there before the below code is the complete code

 articles = [];
constructor() {
    super();
    console.log(typeof articles);
      this.state = {
        articles: this.articles
    }
    // let category = 'top-headlines';
    // let country = 'in';

}

async componentDidMount() {
    const YOUR_API_KEY = 'cant show you this';
    // let q = '';
    let url = `https://newsapi.org/v2/top-headlines?country=in&apiKey=${YOUR_API_KEY}`;
    const FetchNews = async () => {
        const response = await fetch(url);
        const parsedjson = await response.json();
        console.log(parsedjson);
        this.setState({ articles: parsedjson.articles });
    }
    FetchNews();
}

render() {
    return (
        <div className="container p-1" style={{ backgroundColor: '#F0CE57' }}>

            <div className="noogle">
                <h1>Noogle</h1>
                <input type="text" placeholder='Search News' />
            </div>
            <div className="row">
                {this.state.articles.map((element) => {
                    return <div className="col-md-4" key={element.url}>
                        <NewsCard title={element.title} desc={element.description} imgurl={element.urlToImage} url={element.url} />
                    </div>
                })}
            </div>
        </div>

    )
}

}

CodePudding user response:

Because this.state doesn't have a property called articles. It has a property called this which is set to... whatever this.setState returns while trying to set the state to this.articles, which also doesn't exist. This isn't at all what you want:

this.state = {
    this: this.setState({ articles: this.articles })
}

I don't know where you pieced together that example, but it's all wrong. Just initialize the state value to an empty array:

this.state = {
    articles: []
}

Then on initial render you simply have no records to display. And when the AJAX operation completes and sets the new state value you'll have records on the next re-render.

You don't need (or want) your global articles variable. It's going to tempt you to mutate values directly and cause strange bugs.

CodePudding user response:

Why are you setting the state inside constructor. Instead when you are calling this.setState() function , it will set the state of articles Try this code

 articles = [];
constructor() {
    super();
    console.log(typeof articles);
    this.state = {
        articles : []
    }
    // let category = 'top-headlines';
    // let country = 'in';

}
  • Related