0
import { useState } from "react";
function ExampleUseState() {
// const [count, setCount] = useState(0);
// working with objects
const [stateObj, setStateObj] = useState({ count: 0, text: "textInState" });
function increaseCount() {
// setCount((preCount) => (preCount += 1));
setStateObj((preState) => {
return { ...preState, count: preState.count + 1 };
});
}
function decreaseCount() {
// setCount((preCount) => (preCount -= 1));
setStateObj((preState) => {
return {
...preState,
count: preState.count - 1,
text: preState.text === "textInState" ? "SomeNewTextInState" : "textInState",
};
});
}
return (
<Stack alignItems={"center"} sx={{ width: "100%", maxWidth: "40dvw", margin: 2, backgroundColor: "lightblue", padding: 7, borderRadius: 15 }}>
<Typography variant="h6" sx={{ marginBottom: 5 }}>
Example - {stateObj.text}
</Typography>
<Stack direction={"row"} alignItems={"center"} gap={5}>
<Button variant="contained" onClick={decreaseCount} disabled={!stateObj.count}>
-
</Button>
{/* <Typography>{count}</Typography> */}
<Typography>{stateObj.count}</Typography>
<Button variant="contained" onClick={increaseCount}>
+
</Button>
</Stack>
</Stack>
)
}