import{useState}from'react';
export default function App() {
const[state,setState]=useState('mariam');
const[count, setCount]= useState((num)=>{
if (num>=0) {
setCount(count-1)
} else {
setCount(0)
}
});
return (
<div>
<p>{state}</p>
<input onChange={(e)=> setState(e.target.value)} />
<p>{count}</p>
<button onClick={setCount} >click</button>
</div>
)
}
CodePudding user response:
const [count, setCount] = useState(0)
const decrease = () => {
setCount(count => {
return count = count - 1;
})
}
return (
<>
<p>{count}</p>
<input type="button" onClick={decrease}>Decrease</input>
</>
);
CodePudding user response:
To prevent negative values you can add a simple if statement
const [count, setCount] = useState(0)
const decrease = () => {
setCount(prevCount => {
if (prevCount - 1 < 0) return prevCount;
return prevCount - 1;
})
}
return (
<>
<p>{count}</p>
<input type="button" onClick={decrease}>Decrease</input>
</>
);