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

162
Views
How to use setState with nested JSON array object

I'm trying to get data from MongoDb, but setState not updating bookInstances

How can I use setState to update bookInstances? and each array is basically like {"id": ...}

export default class BookInstances extends Component {
constructor(props) {
    super(props)
    this.BookInstance = this.BookInstance.bind(this);
    this.BookInstances = this.BookInstances.bind(this);
    this.state = {
        bookInstances: []
    }
}

componentDidUpdate() {
    axios.get('http://localhost:3001/catalog/bookinstances')
        .then(res => {
            this.setState({ bookInstances: res.data });
        })
}

BookInstance(props) {
    return <li>{props.bookInstance}</li>
}

BookInstances() {
    const bookInstances = this.state.bookInstances;
    if (bookInstances) {
        return bookInstances.map(bookInstance => {
            return <this.BookInstance key={bookInstance} bookInstance={bookInstance.id} />
        })
    }
}

render() {
    return (
        <div>
            <h1>Book Instance List</h1>
            <ul><this.BookInstances /></ul>
        </div>
    )
}

}

Appreciate any assistance ?

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

0

Not sure why you'd use a class component nowadays.. Nonetheless, you're setting state in the wrong lifecycle method.

You'll need to fetch within componentDidMount()

componentDidMount() {
    axios.get('http://localhost:3001/catalog/bookinstances')
        .then(res => {
            this.setState({ bookInstances: res.data });
        })
}
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!