Setting imported data from API to state won't work

I am trying to create a news / articles site for educational purposes using Django and ReactJS.

I have currently created an article model in Django and configured an API for ReactJS. Each article has properties for heading, image, content, tag and quick read. featured and quickreads are booleans. I have successfully configured my ReactJS component to get all articles, however I am having problems filtering articles with article.featured

both true and article.quickreads

also true. Currently my component is in three states: articles, recognized and quickreads. This is what it currently looks like:

class Api extends React.Component{
  constructor(){
    super();
    this.state = {
      articles: null,
      featured: null,
      quickreads: null
    }
  }
  componentDidMount(){
    fetch("http://127.0.0.1:8000/articles/articlesapi/").then(request => request.json()).then(response => this.setState({articles: response}))
    var featured = this.state.articles.filter(article => article.featured === true)
    var quickreads = this.state.articles.filter(article => article.quickreads === true)
    this.setState({featured: featured, quickreads: quickreads})
  }
  render(){
    return (
      <p>Hello  World</p>
    )
  }
}

      

Although the component receives all articles, it does not update featured

and quickreads

. I am getting the following error:

Uncaught TypeError: Cannot read property 'articles' of undefined at componentDidMount (eval at <anonymous>)...

      

Why is this happening?

+3


source to share


1 answer


fetch

is asynchronous, and thus is articles

not set (and is null

) when you try to filter it to set state. Instead, wait for the data to be received:

fetch("http://127.0.0.1:8000/articles/articlesapi/")
  .then(request => request.json())
  .then(response => {
    this.setState({
      articles: response
      featured: response.filter(article => article.featured === true),
      quickreads: response.filter(article => article.quickreads === true)
    });
  });

      



And filter and set the state along with the setting articles

after the data is fetched. I would, however, only keep articles

state and filtering, when you need to do this, you don't have to synchronize all the arrays to make sure they have the same data.

+6


source







All Articles