In React.js, the switch case statement consistently defaults to the default case

Currently, I am working on utilizing <select> tags to update information across components using useContext(). However, I am encountering an issue where the default case is consistently being returned despite the fact that the logged values match the set case values.

This is the renderer for the various select elements:

const selectNames = [
     "Strength",
     "Dexterity",
     "Constitution",
     "Intelligence",
     "Wisdom",
     "Charisma"
]

const options = [
        {
            label: '16',
            value: '16'
        },
        {
            label: '14',
            value: '14-1'
        },
        {
            label: '14',
            value: '14-2'
        },
        {
            label: '12',
            value: '12-1'
        },
        {
            label: '12',
            value: '12-2'
        },
        {
            label: '10',
            value: '10'
        }
    ]

const selectRender = selectNames.map((name, index) => {
   return (
      <>
         <label for={name}>{name}:</label>
         <select name={name} key={index} onChange={handleChange} value={chosenOptions[name] || ''}
                 required={index === 0} id={name.toLowerCase()}>
              <option value=''/>
              {options.filter(({value}) => !isChosenByOther(value, name))
                   .map(({label, value}, oIndex) =>
                        <option value={value} key={oIndex}>{label}</option>)
               }
         </select>
     </>
   )
})

The following code snippet shows the event handler function with a switch case:

The functions like setStrength() are all correctly referenced from the context component. Even if there is an issue in those functions, it should not affect this specific problem since they are not called within this code block.

const handleChange = (ev) => {
        setChosenOptions({...chosenOptions, [ev.target.name]: ev.target.value});
        console.log(ev.target.name)
        switch (ev.target.name) {
            case "Strength":
                setStrength(ev.target.value)
            case "Dexterity":
                setDexterity(ev.target.value)
            case "Constitution":
                setConstitution(ev.target.value)
            case "Intelligence":
                setIntelligence(ev.target.value)
            case "Wisdom":
                setWisdom(ev.target.value)
            case "Charisma":
                setCharisma(ev.target.value)
            default:
                console.log("attribute wasn't successfully changed")
        }
    };

While selecting values within the React app, the corresponding <select> element is correctly identified but the default function is always triggered.

The console logs display:

Intelligence

attribute wasn't successfully changed

Charisma

attribute wasn't successfully changed

Wisdom

attribute wasn't successfully changed

Please let me know if additional sections of code or information are needed.

Answer №1

Make sure to include a break statement after each code block within your switch case logic. Find additional information regarding this best practice by visiting Why do we need break after case statements?

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

What is the solution for resolving an Optional chaining Error in a React project?

Currently, I am delving into the world of react redux while simultaneously constructing an app. One interesting aspect that caught my attention is optional chaining in user authentication. However, this method seems to be throwing an error message. You may ...

Diving into Redux brings up the question of whether to use a generic reducer or a

When working with Redux, what is the preferred approach: Creating entity-specific reducers or utilizing a generic reducer based on strict action keying conventions? The former can result in more boilerplate code but offers loose coupling and greater flexib ...

Encountering an 'undefined' error while attempting to showcase predefined JSON data on an HTML webpage

As I try to display the predefined JSON data from https://www.reddit.com/r/science.json on an HTML page, I keep encountering the message "undefined." Below is a snippet of my HTML code: $.getJSON('https://www.reddit.com/r/science.json', funct ...

What could be the reason why modifications made to $scope in a directive's link function do not appear on the user interface?

The AngularJS directives' link function causes changes to isolate scope data that are not reflected in the UI. Take a look at this example: var myApp = angular.module('myApp', []); myApp.directive('myDirective', function () { ...

What is the best way to trigger the ajax request with the same post parameter upon pressing the browser's back button?

Is there a way to remember the post parameters and resend an AJAX request when the browser back button is pressed? I have searched online and found a couple of methods: Using localsotrage or document.location.hash when the page unloads. Using cookie ...

Having trouble with managing state changes in a React application using Multiple Checkbox components from M

Trying to update the state of multiple checkboxes and then send a POST request. Visually, the checkboxes change, but the form data remains unchanged. Here is the code snippet: export default function AccountInformations(props) { // const { enqueueSnack ...

PHP: AJAX request triggers 500 Internal Server Error

I currently have a dynamic MySQL database that receives regular updates from an AI-generated text. My goal is to display this continuously updating text on a web platform. In order to achieve this, we conducted a simple test as shown below: <head> ...

Displaying received image using Express JS

Currently, I am working on managing two separate Express JS applications. One of them serves as an API, while the other application interacts with this API by sending requests and presenting the received data to users. Within the API route, I am respondin ...

Tips for extracting popular song titles from music platforms such as Hungama or Saavn

I am looking to retrieve the names of the top trending songs/albums from platforms such as Hungama or Saavn. I experimented with web scraping packages available on npm to extract data from websites, including cheerio, jsdom, and request. Eventually, I came ...

Encountered a React error stating: `TypeError: this.state.projects.map is not a

export default class Timeline extends Component{ state = { projects : [], }; async componentDidMount(){ const response = await api.get("/projects"); this.setState({projects: response.data}); } render(){ return ( <div className ...

Is there a way to dynamically set the value of a React Material TextField in Auto Select mode?

Here is a React state: const [filterByInvoiceNo, setFilterByInvoiceNo] = useState( 0 ); This represents a React Material TextField: <TextField size="small" type="number" label="Invoice No&quo ...

Adding TH into a TABLE in Angular 2 by verifying TD elements

I am seeking a way to automatically generate thead and th, using td in the template : <Datatable> <tr #lineSelected *ngFor="let subscription of results"> <td nameColumn="Nom">{{subscription.name}}</td> <td n ...

Unexpected quirks in Canvg conversion: Strange behavior observed while utilizing a fill URL

I am attempting to use the canvg javascript library to convert an svg to canvas. Within the original svg, there is a rectangle with a fill attribute that references a svg pattern. However, when I convert the svg to canvas using canvg: canvg(document.getE ...

Dealing with query strings within routeprovider or exploring alternative solutions

Dealing with query strings such as (index.php?comment=hello) in routeprovider configuration in angularjs can be achieved by following the example below: Example: angular.module('app', ['ngRoute']) .config(function($routeProvider, $loc ...

What troubleshooting steps should I take to address MQTT issues affecting the rendering of my website while using React and Raspberry Pi?

I am facing an issue where I cannot integrate mqtt with my react application on a Raspberry Pi 4. I am seeking assistance to resolve this problem. My setup includes: Distributor ID: Raspbian Description: Raspbian GNU/Linux 11 (bullseye) Release: 11 ...

How do I delete an element from an array in a MongoDB database using Node.js?

When running this query in ROBO 3T, the code executes correctly. However, when attempting to run it in nodejs, the code is not functioning as expected. //schema model const mongoose = require('mongoose'); const imageSchema = mongoose.Schema({ ...

I am puzzled as to why my Details Modal keeps appearing whenever I click anywhere, even when I have specifically added it to only show up on the event of today. Additionally, I am encountering

ERROR Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref at coerceRef (http://localhost:3000/static/js/bundle.js:59386:21) at createChil ...

Using JavaScript, is there a way to modify a JSON parameter within an API?

My API provides JSON data structured like this: [{"NAME":"john","SURNAME":"johny","ADULT":"3","CHILD":"3","BABY":"0",}] In my JavaScript function, I need to send a request to a web service that will update the value of "BABY" from "0" to "1". Can this be ...

Using the ESNEXT, Gutenberg provides a way to incorporate repeater blocks that

If you're like me, trying to create your own custom Gutenberg repeater block with a text and link input field can be quite challenging. I've spent hours looking at ES5 examples like this and this, but still feel stuck. I'm reaching out for ...

The gradual vanishing of principles

Below you will find text fields that I am populating with values that are later utilized in a JavaScript function. These fields are all contained within a form. The issue I am encountering is that when I submit the form, I initially get the correct value ...