Reputation: 7092
I have a state value like this:
const [gamerTag, setGamerTagState] = useState(props.gamerTag);
But I need to change it to a empty string if gamerTag
is null, so I tried this:
if (gamerTag === null) {
gamerTag = "";
}
However now I get a syntax warning that gamerTag
is constant.
How can I set gamerTag
to an empty string if it's null?
Thanks!
Upvotes: 0
Views: 2816
Reputation: 81
It seems like you may have a little bit of a wrong understanding when it comes to using the react state hook.
You should pass the default value of a state in the function call useState("default value")
. Then if you want to update the value of the state depending on some condition you should always use setState(value)
, in your case it is setGamerTag("")
.
Updating the state value directly is wrong because react depends on using the setState(value)
function call to update the state, that's why we use const [state, setState] = useState()
with the const identifier, so that it prevents us from assigning the state directly.
So to fix your error you should do:
if (gamerTag === null){
setGamerTag("");
}
Upvotes: 1
Reputation: 334
you could do:
const [gamerTag, setGamerTagState] = useState(props.gamerTag || '');
or you can do:
if (gamerTag === null) {
setGamerTagState('')
}
If you want to change a value of a state, you always need to use/call the "set...." function. So in your example you need to call "setGamerTagSetate(Value)"
Upvotes: 1