I have this checkbox where the user can check all of the checkbox. I cannot save this in the firestore as it has an error every time I submit it and says:
TypeError: s.indexOf is not a function
and if I check all of checkbox and i'll console.log(state); it shows this:
item1: true
item2: true
item3: true
what I wanted was just when the specific checkbox (item1 and item2) was clicked, it will just output something like this:
item1
item2
Below are the entire codes:
const component = (props) => {
const [state, setState] = useState({
Fever: false,
Headache: false,
Nausea: false,
"Muscle Pain": false,
});
const handleCheckbox = (event) => {
console.log(event.target.value);
setState({ ...state, [event.target.name]: event.target.checked });
};
const handleSubmit = (e) => {
e.preventDefault();
for (const p in state) {
if (!state[p]) delete state[p];
}
try {
const userRef = firestore.collection("users").doc(uid);
const ref = userRef.set({
state,
});
console.log(" saved");
} catch (err) {
console.log(err);
}
};
return (
<Container>
<form onSubmit={handleSubmit}>
<FormGroup style={{ alignContent: "center", padding: "1rem" }}>
<FormControlLabel
control={
<Checkbox
checked={state.Fever}
name="Item1"
color="primary"
value="Item1"
onChange={handleCheckbox}
/>
}
label="Item1"
/>
<FormControlLabel
control={
<Checkbox
checked={state.Headache}
name="Item2"
color="primary"
value="Item2"
onChange={handleCheckbox}
/>
}
label="Item2"
/>
<FormControlLabel
control={
<Checkbox
checked={state.Nausea}
name="Item3"
color="primary"
value="Item3"
onChange={handleCheckbox}
/>
}
label="Item3"
/>
</FormGroup>
<Button type="submit">Submit</Button>
<br />
</form>
</Container>
);
};
export default component;
How can I get the values of item1, item2, and item3 so I can save it as it is in the firestore? Thank you.
Can you try this
const handleSubmit = (e) => {
e.preventDefault();
const newState = {...state};
for (const p in newState) {
if (!newState[p]) delete newState[p];
}
try {
const userRef = firestore.collection("users").doc(uid);
const ref = userRef.set({
newState,
});
console.log(" saved");
} catch (err) {
console.log(err);
}
};