Search code examples
javareactjstypescripttoggleecmascript-2016

Posting Switch Input Boolean Value (React/Typescript)


I'm trying to post the state value of the switch input toggle control, however when i send the post request function submitRecommendation() using a button, i'm getting a JSON parse error: Cannot deserialize instance of `boolean` out of START_OBJECT token; nested exception error.

What am I doing wrong here? and is there a way I can write this function to have multiple toggle controls, without repeating code?

interface IState {
      mentorInfoComplete?: boolean;
      hasChanged?: boolean;
    }
class Component extends React.Component<Props, State> {
  public state: State = {
    mentorInfoComplete: false
  }


  public render() {
    const {} = this.props;
    const { mentorInfoComplete } = this.state;
    const {} = this;

  <div className={classes.switchContainer}>
                    <FormGroup row>
                        <FormControlLabel
                          control={
                            <Switch
                              checked={mentorInfoComplete}
                              onChange={this.handleChange}
                              value={mentorInfoComplete}
                            >Toggle</Switch>
                            }label="YES"
                            />
                      <Typography color="secondary" variant="body1" className={classes.toggleQuestions}>Is this question complete</Typography>
                    </FormGroup>
                  </div>

            <Button
              color="primary"
              className="reviewApplication-back"
              variant="contained"
              type="submit"
              onClick={this.submitRecommendation}>
              Recommend Approval
            </Button>

  private handleChange() {
     this.setState({
      mentorInfoComplete: true
   });
   console.log(this.state);
  }

private async submitRecommendation() {
  const { 
    application,
    mentorInfoComplete
   } = this.state;

    if (!application) {
        return;
      }

      try {
        await axios.post(
          `/mentorApplication/${match.params.applicationId}/checklist`,
          {
            mentorInfoComplete: { mentorInfoComplete }
                  }
            );
    }
    }

Solution

  • Without knowing the API, my guess is that this is the offending line: mentorInfoComplete: { mentorInfoComplete }

    You're essentially making it mentorInfoComplete: { true } when I'm guessing what you want is mentorInfoComplete: true

    Try getting rid of the extra brackets and see if that helps?