react hook useState throwing TypeError: Assignment to constant variable error

Viewed 39

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('abc1@gmail.com');

 if (regionData === 'us')) {
    userId = 'abc2@gmail.com';
  } else {
    userId = 'abc3@gmail.com';
  }

  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.

4 Answers

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

useEffect(() => {
  if (regionData === 'us')) {
  setUserId('abc2@gmail.com')
} else {
  setUserId('abc3@gmail.com')
}}, [])

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

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

useEffect(() => {
  if (regionData === 'us')) {
     setUserId('abc2@gmail.com');
  } else {
     setUserId('abc3@gmail.com');
  }
}, []);

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

Since you are doing it the first time, why not do it at assignment?

const [userId, setUserid] = useState(
  regionData === 'us' 
    ? 'abc2@gmail.com'
    : 'abc3@gmail.com'
);

If you want to update it when regionData changes, in that case, you will need to use useEffect.

const getUserId = () => {
  if (regionData === 'us') {
    return 'abc2@gmail.com';
  } else {
    return 'abc3@gmail.com';
  }
};

const [userId, setUserid] = useState(getUserId());

useEffect(() => {
  setUserId(getUserId());

  // Provided, regionData is a react state coming either 
  // from props or defined in this component
}, [regionData]);

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