Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
Append array from constructor in react

I have this class component where I'd like to fetch the response from server to an state array so I can pass further the elements to another component as props, so far I have this:

export default class MainApp extends Component {
state = {
    posts: [],
}

constructor(props){
    super(props);

    const request = new FetchRequest();
    request.setAmount(this.props.amount);
    request.setUserid(this.props.token);
    request.setSeenpostsList(this.props.seenPosts);
    
    var stream = client.fetchPosts(request, {});
    stream.on('data', function(response) {
        this.setState({
            posts: [...this.state.posts, response.array]
        })
    });
}

render(){
    return(
    <div className="main-app">
        <Navbar />
        <Postbox token = {this.props.token}/>
        {this.state.posts.map(element => 
            <Postcard username = {element[0]}/>
         )}
    </div>
    )
}

With this code I get TypeError: Cannot read properties of undefined (reading 'posts').

What is the correct way to do it?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your state needs to be initialised within the constructor() {}

constructor(props) {
  super(props);

  this.state = {
    posts: []
  }
}

Here's info you might also want to read

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!