Search code examples
javascriptreactjstypescriptecmascript-2016

Function to Handle Multiple Switch Controls in React/Typescript


What I'm trying to do is send a post request of multiples switch control however I think they're has to be an easier way to send the requests instead of individually writing a request for each switch input. How can I consolidate or write a function that can do this cleanly? Using Typescript/React. Question updated below:

UPDATE: What I want to do is send the state of the switch input control as a toggle. ie. when the switch control is set to yes/no, then it sends a post request to the server

    interface IState {
  checkedA?: boolean;
  checkedB?: boolean;
}

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

 <div className={classes.switchContainer}>
                <FormGroup row>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={this.state.checkedA}
                          onChange={this.handleChange}
                          value="checkedA"
                        >Toggle</Switch>
                        }label="YES"
                        />
                  <Typography color="secondary" variant="body1" className={classes.toggleQuestions}>Question 1</Typography>
                </FormGroup>
              </div>

     <div className={classes.switchContainer}>
                    <FormGroup row>
                        <FormControlLabel
                          control={
                            <Switch
                              checked={this.state.checkedB}
                              onChange={this.handleChange}
                              value="checkedB"
                            >Toggle</Switch>
                            }label="YES"
                            />
                      <Typography color="secondary" variant="body1" className={classes.toggleQuestions}>Question 2</Typography>
                    </FormGroup>
                  </div>
)}

<Button
 onClick={this.submitRecommendation}>
Send Request</Button



 await axios.post(
      `/test/testpost`,
      {  
       post request from click of button would go in here
      } catch (err) {
}
);


Solution

  • Well here's an example of how you can access the inputs programmatically on form submission:

    private handleSubmit = (e: React.FormEvent): void => {
      e.preventDefault();
      // We want the form as a starting point to traverse the DOM
      const form = e.target;
      // It seems like we can be relatively sure that all the information 
      // we want is contained in the form's inputs, so we'll select them all
      const inputs = form.querySelectorAll('input');
      // With the NodeList inputs (a DOM data type), we can use .forEach 
      // to check out all the nodes by their type
      inputs.forEach(input => {
        // Accessing the name and value will give you all
        // the information you need to build up a POST request
        switch(input.type) {
          case 'checkbox':
            console.log('The checkbox is called', input.name, 'and its checked state is', input.checked);
            break;
          case 'text':
            console.log('The text input is called', input.name, 'and it says', input.value);
            break;
        }
      });
    }
    

    And here's an example of how you could potentially build up a request object in the .forEach loop, building up an object to send in your request. You can do this quite easily if you make sure to use the right name prop for each item.

    // in the above method
    const request = {};
    inputs.forEach(input => {
      // Somehow map the input name and value to your data model you're updating
      request[input.name] = input.value;
    });
    await axios.post(/* use request object here */);
    

    Hopefully this is plenty to get you started, but feel free to comment if there are any specific implementation details you'd like to discuss! :D