0

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

breking bed
  • 135
  • 2
  • 14

3 Answers3

2

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
Mohammad Faisal
  • 2,265
  • 1
  • 10
  • 16
2

you can initialize state lazily

const [buttonName, setButtonName] = useState(() => {
    return localStorage.getItem('address') ? 'Wallet Connected' : 'Connect Wallet'
  });
linusw
  • 1,140
  • 3
  • 9
1

Just use the ternary operator directly inside

const [buttonName, setButtonName] = useState( localStorage.getItem('address') ?'Wallet Connected' :'Connect Wallet');

SlothOverlord
  • 1,655
  • 1
  • 6
  • 16