I have a checkbox and when it's checked/unchecked, it writes true or false in the console, however, when I try and save the value, it's always passing false.
html:
<input type="checkbox"
name="Status"
value="Status"
onChange={(e) => {carStatus(e)}) />
const CarState = {
carId: 0,
Make: "",
Model: ""
Active: "" //this is a bit in the DB
}
const [carMake, setCarMake] = useState(CarState);
const [carModel, setCarModel] = useState(CarState);
const [carActive, setActive] = useState(CarState);
const carStatus = (e) => {
const status = e.target.checked;
if(status)
{
console.log("checked " status);
setCarActive({ ...carActive, status});
}
else
{
console.log("checked" status);
setCarActive({ ...carActive, status});
}
const saveCar = () => {
var data = {
make: carMake.CarMake,
model: carModel.Model,
active: saleActive.Active //always false even if checkbox is checked
};
//passes data to the API
}
Is there a better way to do this or a different way? I can see true/false in F12 if the checkbox is checked or not, however, just passes false when I click the save button [saveCar function]
CodePudding user response:
You are not updating the nested Active
state, you are adding a status
property and not referencing it. Use the checked
value and update the Active
property in state.
const [carActive, setCarActive] = useState(CarState);
...
const carStatus = (e) => {
const { checked } = e.target;
console.log("checked " checked);
setCarActive(carActive => ({
...carActive, // <-- shallow copy previous state
Active: checked, // <-- set new Active checked value
}));
}
In the input you should reference the state. Use the checked
prop/attribute/
<input
type="checkbox"
name="Status"
value="Status"
checked={carActive.Active} // <-- set the checked prop of input
onChange={carStatus}
/>
In saveCar
reference the correct state being updated. Ensure all the properties being accessed match the carState
properties.
const saveCar = () => {
var data = {
make: carMake.Make,
model: carModel.Model,
active: carActive.Active
};
//passes data to the API
}
Working Demo
CodePudding user response:
Do something like this
<input
type="checkbox"
name="Status"
checked={carActive.Active === true}
onChange={(e) => setActive(state=>({...Active:e.target.checked}))) />