BugHunterUK
BugHunterUK

Reputation: 8938

Component not updating when state changes

This is the first time I'm using React without JSX so I may have made an obvious error, but I can't seem to figure out why my component is not updated.

I make a xhr request in componentDidMount and attempt to set this.state.isLoading to false. This should cause the loading message to be removed once the xhr request has finished.

Here's my code:

import React from 'react'
import request from 'superagent'

export class SurveyList extends React.Component {
  constructor () {
    super()
    this.state = {
      error: false,
      surveys: [],
      isLoading: true
    }
  }

  componentDidMount () {
    request
      .post('/surveys')
      .set('accept', 'json')
      .end((err, res) => {
        if (err) this.state.error = err
        this.state.isLoading = false
      })
  }

  render () {
    const items = this.state.surveys.map(survey => React.createElement('li', survey))
    const loading = React.createElement('p', null, 'Loading ...')
    const list = React.createElement('ul', null, items)
    return this.state.isLoading ? loading : list
  }
}

I render like so:

const surveyListElem = document.getElementById('survey-list')
if (surveyListElem) {
  ReactDOM.render(
    React.createElement(SurveyList),
    surveyListElem
  )
}

Upvotes: 0

Views: 44

Answers (1)

Dan Inactive
Dan Inactive

Reputation: 10060

Setting the state directly will have no effect. You need to use setState() instead to trigger a re-render.

Upvotes: 3

Related Questions