Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

53
Views
Make button clickable after state changes

So I have this count where I will increment once the button with handleFollow() is clicked (i have multiple buttons with handleFollow() and I'm only showing one here). How do keep track of the count and then change the allowNext to false once the count is more than 3 so that I can make the button clickable.

let count = 0;
const [allowNext, setAllowNext] = useState(true)
const [followed, setFollowed] = useState({
    1 : false,
    2 : false,
    3 : false,
    4 : false,
    5 : false,
  })

const handleFollow = (idx) => {
    const val = !followed[idx]
    setFollowed(prev => ({...prev, [idx] : val}))
    count += 1
}

<div>
     <Button onClick={() => {handleFollow(5);}} style={buttonStyle1} disabled={clicked[4]}>Continue</Button> 
</div>

// disabled={allowNext=false} only when count is more than 3 to make it clickable
<div>
     <Button style={buttonStyle2} disabled={allowNext} onClick={() => {setSelectedForm(2)}}>Next page</Button>
</div>

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

You define count as state first, and then you can add useEffect for this case

const [count, setCount] = useState(0);

useEffect(() => {
    if (count > 3){ 
      setAllowNext(false);
    }

}, [count]);

And change the way you increment in handleFolow instead of count += 1, use setCount(prev => prev+1)

Alternative approach would be, keep count as state and keep setCount increment, but instead of useEffect, after you increment count you directly check

if (count > 3){ 
  setAllowNext(false) 
}

However I am not sure if this is safe because we access directly after the changing the state, bug might occur, so first approach would be my way to go

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs