I have a project in React and Typescript and am creating a Like button and created an if/else statement as so:
const [count, setCount] = useState(0);
const [iconFill, setFill] = useState('gray');
const favoriteCount = () => {
if(iconFill == 'red') {
setCount(count - 1 );
setFill('gray');
}
else {
setCount(count + 1);
setFill('red');
}
}
The code works as expected but I am wondering if there is a more concise way to write it, I tried using a ternary statement:
iconFill == 'red' ? setCount(count - 1 ) && setFill('gray') : setCount(count + 1) && setFill('red');
I am unsure of why this doesn't produce the same result and am also getting the following Typescript error:
An expression of type 'void' cannot be tested for truthiness
... ? ... : ...be any better? Write code that you can understand by only looking at it. Anything else is the job of a specialized tool.voidtype cannot be casted toboolean. State modifiers returnsvoidtype.