Search code examples
reactjssuperagent

Grabbing React form field values for submission


Given a React form, I'm having trouble getting the value from the selected radio button, and text box if other is selected. I should be able to pass the fields into the send() for the post, but not sure how to grab them.

class CancelSurvey extends React.Component {
constructor (props) {
  super(props)
  this.state = {
    reasons: [],
    reason: {}
  }
  this.processData = this.processData.bind(this)
  this.handleSubmit = this.handleSubmit.bind(this)
  this.otherSelected = this.state.reason === "otheroption";
}

componentDidMount () {
  this.fetchContent(this.processData)
}

/**
 * Fetch reasons
 */

fetchContent (cb) {
  superagent
    .get('/api/user/survey')
    .then(cb)
}

/**
 * Set state after reasons have been fetched
 * @param data
 */

processData (data) {
  this.setState({
    reasons: data.body
  })
}

handleSubmit (e) {
  e.preventDefault()
  let reason = this.state.reason
  if (reason === 'otheroption') {
    reason = this.state.otherreason
  }
  console.log(reason)
  superagent
    .post('/api/user/survey')
    .send({
      optionId: this.state.reason.reason_id,
      optionText: this.state.reason.client_reason,
      otherReasonText: this.state.otherreason
    })
    .then(function (res) {
      console.log('Survey Sent!')
    })
}
  /**
   * render
   */
  render (props) {
    const content = this.props.config.contentStrings
    const reason = this.state.reasons.map((reason, i) => {
      return (
        <div className='fieldset__item' key={i}>
          <label>{reason.client_reason}</label>
          <input type='radio'
            id={reason.reason_id}
            value={reason.client_reason}
            name='reason'
            checked={this.state.reason.reason_id === reason.reason_id}
            onChange={() => this.setState({reason})} />
        </div>
      )
    })

    return (
      <div className='survey'>
        <h2 className='heading md'>{content.memberCancel.exitSurvey.heading}</h2>
        <p className='subpara'>{content.memberCancel.exitSurvey.subHeading}</p>
        <form id='exit-survey' onSubmit={this.handleSubmit}>
          <fieldset className='fieldset'>
            { reason }
            <label>Other reason not included above:</label>
            <input type='radio'
              id='otheroption'
              name='reason'
              value={this.state.reason.otherreason}
              onChange={() => this.setState({reason:{reason_id: 70, client_reason: 'other'}})} />
            <input className='valid'
              type='text'
              id='otheroption'
              name='othertext'
              placeholder={content.memberCancel.exitSurvey.reasonPlaceholder}
              onChange={(event) => this.setState({otherreason: event.target.value})} />
          </fieldset>
          <div className='footer-links'>
            <button className='btn btn--primary btn--lg' onClick={this.handleSubmit}>{content.memberCancel.exitSurvey.button}</button>
          </div>
        </form>
      </div>
    )
  }
}

export default CancelSurvey

Solution

  • Your variables aren't correct. I've update them to what I think is correct.

    handleSubmit (e) {
      e.preventDefault()
      superagent
        .post('/api/user/survey')
        .send({
          optionId: this.state.reason.reason_id,
          optionText: this.state.reason.client_reason,
          otherReasonText: this.state.reason.otherreason
        })
        .then(function (res) {
          console.log('Survey Sent!')
        })
        .catch(function (err) {
          console.log('Survey submission went wrong...')
        })
    }
    /**
     * render
     */
    render (props) {
        const content = this.props.config.contentStrings
        const reason = this.state.reasons.map((reason, i) => {
            return (
                <div className='fieldset__item' key={i}>
                    <label>{reason.client_reason}</label>
                    <input 
                        type='radio'
                        id={reason.reason_id}
                        name='reason'
                        checked={this.state.reason.reason_id === reason.reason_id}
                        value={reason.client_reason}
                        onChange={() => this.setState({reason})} />
                </div>
            )
        })
    
        return (
            <div className='survey'>
                <h2 className='heading md'>{content.memberCancel.exitSurvey.heading}</h2>
                <p className='subpara'>{content.memberCancel.exitSurvey.subHeading}</p>
                <form id='exit-survey' onSubmit={this.handleSubmit}>
                    <fieldset className='fieldset'>
                        { reason }
                        <label>Other reason not included above:</label>
                        <input type='radio'
                            id='otheroption'
                            name='otheroption'
                            value={this.state.reason.otherreason}
                            checked={this.state.reason.reason_id === 0}
                            onChange={() => this.setState({ reason: {reason_id: 0, client_reason: ""} })} />
                        <input className='valid'
                            type='text'
                            id='othertext'
                            name='othertext'
                            value={this.state.reason.otherreason}
                            placeholder={content.memberCancel.exitSurvey.reasonPlaceholder}
                            onChange={(event) => this.setState({ reason: {reason_id: 0, client_reason: "", otherreason: event.target.value} })} />
                    </fieldset>
                    <div className='footer-links'>
                        <button className='btn btn--primary btn--lg' onClick={this.handleSubmit}>{content.memberCancel.exitSurvey.button}</button>
                    </div>
                </form>
            </div>
        );
    }