Home > Mobile >  react hook useState throwing TypeError: Assignment to constant variable error
react hook useState throwing TypeError: Assignment to constant variable error

Time:09-19

I am working on some code, and I am stuck on this error. I am using the useState hook when a condition is true, I want to change value & show that value in Input box I get the following error: Uncaught TypeError: Assignment to constant variable. I understand that it if you define it as const you cant change its value, but I don't get why.

import React, { useState } from 'react';

const Demo = props=> {

const [userId, setUserid] = useState('[email protected]');

 if (regionData === 'us')) {
    userId = '[email protected]';
  } else {
    userId = '[email protected]';
  }

  return (
    <div className="col-sm-8">
             <input type="text" className="form-control rounded-10" value={userId} name="userid" onChange={(e) => { setUserid(e.target.value); }}  />
    </div>
  )

}
export default Demo;

Any suggestions or advice is greatly appreciated.

CodePudding user response:

If you want to change state, you should use setter function instead of assign value to variable. In your case this would be a correct approach

   useEffect(() => {
if (regionData === 'us')) {
    setUserId('[email protected]')
  } else {
    setUserId('[email protected]')
  }}, [])
    

Also see react lifecycle methods and useEffect hook. In this case it might be ComponentDidMount

CodePudding user response:

userId is not to be modified directly. You will have to update in a useEffect.

useEffect(() => {
  if (regionData === 'us')) {
     setUserId('[email protected]');
  } else {
     setUserId('[email protected]');
  }
}, []);

if regionData is part of props, do pass regionData as a dependency to the useEffect.

CodePudding user response:

To set userId you need to call setUserId function like this:

setUserId('blablabla')

You can change the value of a constant variable but not its type.

i.e:

const a = 0

a = 100 // no error
a = 'toto' //will throw an error
  • Related