I want to add if condition inside of use state. So here is my code example:
const [buttonName, setButtonName] = useState('Connect Wallet');
const changeButtonName = () => {
localStorage.getItem('address') ? setButtonName('Wallet Connected') : setButtonName('Connect Wallet');
};
so I want to add changeButtonName into useState. The reason why I want to do it is as soon as the page renders I want to check if there is address in local and if there is I want to set the name of the button.
Thanks
CodePudding user response:
It's not correct to add conditions inside useState Do the following thing instead.
useEffect(() => {
changeButtonName()
},[])
The empty dependency array makes sure that the function gets called on the first render
CodePudding user response:
you can initialize state lazily
const [buttonName, setButtonName] = useState(() => {
return localStorage.getItem('address') ? 'Wallet Connected' : 'Connect Wallet'
});
CodePudding user response:
Just use the ternary operator directly inside
const [buttonName, setButtonName] = useState( localStorage.getItem('address') ?'Wallet Connected' :'Connect Wallet');