changing the validation function from using if statements to utilizing switch statements

Currently, I am refactoring a form in react and planning to offload most of the state and logic to the parent component. This decision is made because the parent's state will be updated based on the form submission results. However, I encountered an issue while trying to implement a switch statement, which was suggested for better performance in the long run.

The Validate function is where my struggle with integrating a switch statement persists.

 import React from 'react'
    import styles from './style.addLibForm.css'

class AddLibForm extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
            input: {
                title: "",
                content: "",
                imgURL: ""
            },
            blurred: {
                title: false,
                content: false,
                imgURL: ""
            },
            formIsDisplayed: this.props.toggle
        };
      }


handleInputChange(newPartialInput) {

  this.setState(state => ({
    ...state,
    input: {
      ...state.input,
      ...newPartialInput
    }
  }))

}

handleBlur(fieldName) {
this.setState(state => ({
    ...state,
    blurred: {
        ...state.blurred,
        [fieldName]: true
      }
  }))
}

***//TURN INTO SWITCH STATEMENT!***
validate() {
    const errors = {};
    const {input} = this.state;

    switch(true) {
        case !input.title:
            errors.title = 'Title is required';
            break;
        case !input.content:
            errors.content = 'Content is required';
            break;
        case !input.imgURL:
            errors.imgURL = 'Image URL is required';
            break;
        default:
            console.log('No validation errors');
    }

    console.log(Object.keys(errors).length === 0);
    return {
        errors,
        isValid: Object.keys(errors).length === 0
    };
}


render() {
  const {input, blurred} = this.state;
  const {errors, isValid} = this.validate();


  return (

    <div className="flex">
      <form
        className={styles.column}
        onSubmit={(e) =>
          { e.preventDefault();
            this.setState({})
            return console.log(this.state.input);
            }}>

        <h2> Add a library! </h2>


          <label>
            Name:
            <input
              className={styles.right}
              name="title"
              type="text"
              value={input.title}
              onBlur={() => this.handleBlur('title')}
              onChange={e => this.handleInputChange({title: e.target.value})}/>
          </label>
          <br/>



          <label>
            Content:
            <input
              className={styles.right}
              name="content"
              type="text"
              value={input.content}
              onBlur={() => this.handleBlur('content')}
              onChange={e => this.handleInputChange({content: e.target.value})}/>
          </label>
          <br/>


          <label>
            Image URL:
            <input
              className={styles.right}
              name="imgURL"
              type="text"
              value={input.imgURL}
              onBlur={() => this.handleBlur('imgURL')}
              onChange={e => this.handleInputChange({imgURL: e.target.value})}/>
          </label>
          <br/>

        <p>
            <input className={styles.button} type="submit" value="Submit" disabled={!isValid}/>
        </p>

        {/* CSS THESE TO BE INLINE WITH INPUTS */}
        <br/>
        {blurred.content && !!errors.content && <span>{errors.content}</span>}

        <br/>
        {blurred.title && !!errors.title && <span>{errors.title}</span>}
        <br/>
        {blurred.imgURL && !!errors.imgURL && <span>{errors.imgURL}</span>}

      </form>
    </div>
  );
}
  }

export default AddLibForm

I have been attempting to incorporate the switch statement inside the validate function, but I've tried several approaches including inputs, errors, this.state.input, this.state.errors, and {input}, however, it's not functioning as expected. Any guidance on what I might be missing?

Answer №1

Switch statements are most useful when you have to compare a single variable with multiple values

if(x === 1){
//...
} else if(x === 2) {
//...
} else if(x === 3) {
//...
} else {} {
//...
}

=>

switch (x) { 
  case 1: 
  //... 
  break;
  case 2: 
  //... 
  break;
  case 3: 
  //... 
  break;
  default: 
  //...
}

as it clearly represents the mapping between "1 variable to many values."

In your specific situation, you are not comparing one variable to multiple values; instead, you are checking multiple variables for existence by semantically comparing them to a truthy value, so using switch would not be ideal.

It is advisable to keep the current code structure since each if statement is evaluating different conditions and remains readable.

For more detailed guidance on handling conditions efficiently, you can refer to this article.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

If a particular <td> element is present on the page, exhibit a unique <div>

I have a webpage with various HTML elements. <div class="alert">Your message was not sent.</div> <p class="pending">Email Pending</p> I would like to display the div.alert only if the p.pending is present. Is ...

The issue with session storage persisting even after closing the iframe

Encountering a persistent issue where the sessionStorage remains populated even after closing an iframe and opening another one with the same destination. I assumed that the sessionStorage would be reset and start afresh each time. The iframe is contained ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

Implement a class attribute to the parent <div> element using React and TypeScript

I'm trying to figure out how to achieve this task. I need to assign a class upon clicking on an element that is not directly in my code, but rather in one of its parent elements. My initial thought was to accomplish this with jQuery using the followi ...

I am experiencing excessive paper skipping in my printer

I have been using the 80 column dot matrix printer. However, after each printout, the paper skips two times resulting in a lot of wasted paper. How can I resolve this issue? Currently, I am only utilizing the window.print() JavaScript function. Are there ...

Leveraging client API callback variables within a Node.js backend system

If I send a request on the client side using the code snippet below public/foo.js function bar() { fetch('https://api.github.com/') .then(response => response.json()) .then(data => { console.log(data) }) .catch( ...

Issue with Material UI: Warning - The <td> element should not be placed inside a <div> element

In my project, I am utilizing React, typescript, and Material UI. One of the components I have created is a standard "Create user form" with basic input fields for username, name, email, etc. I have also included buttons for "Edit" and "Delete." While ever ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

Having issues with my CodePen React code and its ability to display my gradient background

I will provide detailed descriptions to help explain my issue. Link to CodePen: https://codepen.io/Yosharu/pen/morErw The problem I am facing is that my background (and some other CSS elements) are not loading properly in my code, resulting in a white bac ...

Can anyone explain the functionality of passport.initialize() in the context of Node.js and Express

I am currently working on implementing the passport module in my application. After reading some manuals, I found this: app.use(passport.initialize()); app.use(passport.session()); Can someone explain what app.use(passport.initialize()) does exactly? I ...

What is the most effective way to transfer an array from one PHP file to a different JavaScript file?

Utilizing AJAX to send a request to another php page and retrieve the result of a query, I originally used xmlhttprequest to pass the php logic along with the query information. However, I wanted to separate the presentation logic from the actual code logi ...

What sets usePreloadedQuery apart from useQueryLoader?

I've been exploring graphQL and the react-relay library. These are the key points I've covered: Rendering Queries: where usePreloadedQuery is introduced. Fetching Queries for Render: where useQueryLoader is introduced. To keep it simple, I&apo ...

Is it possible to use combox to deactivate the buttons?

My goal is to deactivate the button as soon as I select a value from the drop-down list. For example, here's what I have: <select name =""> <option> disable </option> <option> enable </option> </select> <input ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Encountering Unmet Dependency Issue When Running 'npm install' on Laravel in Windows 8

Currently, I am in the process of working on a Laravel project and looking to utilize Elixir to handle my front-end tasks. After running 'npm install', I encountered a warning stating "npm WARN unmet dependency". What steps should I take in order ...

Display loading spinner in Material-UI Table while fetching data

Is it possible to display a Circular progress indicator while waiting for data to populate the table? How can this be accomplished? Currently, the table shows No records to display until the data is retrieved from the server. https://i.stack.imgur.com/Ljq ...

Utilizing PHP with WordPress: Execute the specified .js file if the link includes the ID "124"

I am currently using WordPress on my local server and I want to set up a redirect after a user submits the contact form through the Contact Form 7 Plugin. I am looking to redirect them to a specific page, but so far, the plugins I have tried have caused th ...

How to Disable Autofill Background Color in React Material UI

I have been struggling to find a solution for removing the background color of autofill selection. Whenever I use an autofill value, the background color changes to a different color. View Current Issue I have tried using the workaround: -webkit-box-sha ...

Changing the value in a URL String using JavaScript

I am in possession of a String that contains a URL resembling the following: var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jg ...

The compatibility between JSON and the CORS header 'Access-Control-Allow-Origin' is crucial

I am trying to obtain the value from a JSON file that is located on the server. To retrieve this value, I am using AJAX. However, when checking the console for errors, I receive the following message: Cross-Origin Request Blocked: The Same Origin Poli ...