Home > Net >  Unable to modify a variable inside a function in JS
Unable to modify a variable inside a function in JS

Time:08-07

I'm using React, so I don't know if the rules are different for it, but I'm making a voice assistant, I want the variable myVar to be modified in the switch statement in the function myFunc. Here is what I tried now:

  let myVar = "x";
  const myFunc = () => {
    myVar = "Welcome Back!";
    switch (transcript) {
      case "hello":
      case "hey":
      case "hi":
        const greetingArray = ["Hello", "Hello! Happy day!"];
        const randomItem =
          greetingArray[Math.floor(Math.random() * greetingArray.length)];
        myVar = randomItem;
        TTS(myVar, "english");

        break;
      case "bye":
        TTS("Goodbye", "english");
        break;
    }

    return myVar;
  };

  return (
    <div>
      <p>Microphone: {listening ? "on" : "off"}</p>
      <button onClick={SpeechRecognition.startListening}>Start</button>
      <button onClick={SpeechRecognition.stopListening}>Stop</button>
      <button onClick={resetTranscript}>Reset</button>
      <button
        onClick={() => {
          console.log({ transcript });
        }}
      >
        Click
      </button>

      <p>{transcript}</p>
      <p>{myVar}</p>
      <button onClick={console.log(myVar)}>Button</button>
      <button onClick={myFunc}>Speak</button>
    </div>
  );

But the problem is that it is not working. It is modified inside the function, but it is not coming outside it.

Can anyone please help me?

CodePudding user response:

if you're using react.js, maybe you should define your variable in the state of the component

for example

const myComponent = () => {
  const [myVar, setMyVar] = useState("");

  const yourFunction = () => {
    ... 

    setMyVar(new_value)
  }

  return <div>{ myVar }</div>;
}

Just use setMyVar to update your new value.

hope this might help you.

CodePudding user response:

Maybe try defining the variable in the function?

   const myFunc = () => {
    let myVar = "x";
    myVar = "Welcome Back!";
    switch (transcript) {
      case "hello":
      case "hey":
      case "hi":
        const greetingArray = ["Hello", "Hello! Happy day!"];
        const randomItem =
          greetingArray[Math.floor(Math.random() * greetingArray.length)];
        myVar = randomItem;
        TTS(myVar, "english");

        break;
      case "bye":
        TTS("Goodbye", "english");
        break;
    }

    return myVar;
  };
  • Related