React.useState on click the value is not changing

clock icon

asked 301 days agoAsked

message

2Answers

eye

46Views

import React from "react"

export default function App() {
    let [isGoingOut, setisGoingOut] = React.useState("Yes")
    function changeState(){
        setisGoingOut(prevValue => {
            return prevValue = "Yes" ? "No" : "Yes"
        })
    }
    
    return (
        <div className="state">
            <h1 className="state--title">Do I feel like going out tonight?</h1>
            <div className="state--value" onClick={changeState}>
                <h1>{isGoingOut}</h1>
            </div>
        </div>
    )
}

 

When i click the Value Yes its changing to No. But when i click the value No its not changing to Yes. What is the mistake here?

2 Answers

This is where the error occurs. 
prevValue = "Yes" ? "No" : "Yes"

You are basically assigning prevValue the value 'Yes'. This statement always returns true. To make it work, modify your conditional statement to
prevValue === "Yes" ? "No" : "Yes".

Happy Coding!

import React from "react"

export default function App() {
    let [isGoingOut, setisGoingOut] = React.useState(true)
    function changeState(){
        setisGoingOut(prevValue =>  !prevValue)
    }
   
    return (
        <div className="state">
            <h1 className="state--title">Do I feel like going out tonight?</h1>
            <div className="state--value" onClick={changeState}>
                <h1>{isGoingOut ? "Yes" : "No"}</h1>
            </div>
        </div>
    )
}
 
 

Write your answer here

Top Questions