TransWikia.com

handling multiple useState inside conditional ternary

Stack Overflow Asked by Kachi Cheong on January 27, 2021

So for some reason I can’t use my than one useState in my conditional ternary, but on the second example i can.

This first one has 2 useStates and seems to work.

    const nextAnswer = () => {
        (videoIndex === videoData.length - 1) ? 
            setVideoIndex(0):setVideoIndex(prevWord => prevWord + 1);
        setShowResults(false)
    }

but this one doesn’t seem to want to work.

    const [showResults, setShowResults] = useState(false)
    const [showButton, setShowButton] = useState("Show Answer")

    const showMe = () => {
        (setShowResults === false) ? 
            setShowResults(true); setShowButton("Hide Answer"):
            setShowResults(false); setShowButton("Show Answer")
    }

Can anyone help me with this?

2 Answers

You really shouldn't use a ternary for code blocks. If you need help getting the second snippet to function correctly I would suggest you look at the logic from a different perspective.

From what I can tell you want to

  1. Toggle the showResults value
  2. Conditionally render "Show/Hide Answer" based on showResults value

code

const [showResults, setShowResults] = useState(false);

...

const showMe = () => {
  setShowResults(show => !show);
};

...

<button>{showResults ? "Hide" : "Show"} Answer</button>

If you really must use two pieces of state (even though the button text can be derived from the first) then I suggest this:

const showMe = () => {
  setShowResults(show => !show);
  setShowButton(setShowResults ? "Show Answer" : "Hide Answer");
}

Basically just trying to keep the code as DRY as possible.

Correct answer by Drew Reese on January 27, 2021

You have a problem in your ternary, you cant run 2 statements. Just use a if statement

if (!showResults) {
    setShowResults(true);
    setShowButton("Hide Answer");
} else {
    setShowResults(false);
    setShowButton("Show Answer");
}

Answered by topched on January 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP