1

While using multiple state variables in my App.jsx I wanted to set the value of one state equal to that of another state.

const [exchangeRatio, setExchangeRatio] = useState();
const [toCurValue, setToCurValue] = useState();

function foo()
{
   setToCurValue(exchangeRatio);
}

On console.log(exchangeRatio);

{exchangeRatio: undefined}
exchangeRatio: undefined
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

On further

console.log({exchangeRatio}.valueOf());
>>Undefined

I am new to React if there are ways to do the same feel free to write.

2
  • If the 2nd state has the value of the 1st state then why do you even need two states? Commented Jul 18, 2020 at 16:39
  • They can be different as well it's just one particular scenario where i want them same. Commented Jul 18, 2020 at 16:44

1 Answer 1

2
const [exchangeRatio, setExchangeRatio] = useState();
const [toCurValue, setToCurValue] = useState();

The above statement denotes that you are declaring a state with values stored in exchangeRatio and toCurValue respectively and those states can be modified only using setExchangeRatio and setToCurValue methods respectively.

While you declare a state using useState(), you are expected to specify the initial value of the state inside the useState() as a parameter. For eg. if you want the initial value of exchangeRatio to be 10, then you must write it as -

const [exchangeRatio, setExchangeRatio] = useState(10);

Now, since you haven't provided an initial state value, you are getting the console logged output as undefined. Once, you properly initialize it with the proper value, you can directly use the state and the stored value will be returned to you.


So, suppose you want to set toCurValue's value to be equal to exchangeRatio's value (which has been initialised properly), then you can either do it while writing useState() or using the setToCurValue in following ways -

const [toCurValue, setToCurValue] = useState(exchangeRatio);

OR

setToCurValue(exchangeRatio);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it wasn't working because I had not initialized the state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.