I would say, create a local state, say
const [submited, setSubmited] = useState(true);
then on submit, change the state to true, and in your useEffect use "submitted" state also as a dependency along with id. OnHandleChange set "submitted" to false so we can submit again.
if (id) {}
becomes
if (id && submitted) {}
in the UseEffect.
function CreateGroup({ currentUser }) {
const [name, setName] = useState("");
const [group, setGroup] = useState([]);
const [submited, setSubmited] = useState(true);
const handleChange = (e) => {
const { value, name } = e.target;
setName({
[name]: value,
});
setSubmited(false);
};
const handleSubmit = async (e) => {
e.preventDefault();
createGroup(currentUser, name.name);
setSubmited(true);
};
let id = currentUser ? currentUser.id : "";
useEffect(() => {
const fetchData = () => {
if (id && submitted) {
firestore
.collection("users")
.doc(id)
.collection("group")
.get()
.then(function (snapshot) {
snapshot.forEach(function (doc) {
// console.log(doc.id, " => ", doc.data());
setGroup({
id: doc.id,
...doc.data(),
});
});
});
}
};
fetchData();
}, [id, submitted]);
return (
<div>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="exampleInputTitle">Group Name</label>
<input
type="text"
className="form-control"
name="name"
id="name"
aria-describedby="TitleHelp"
onChange={handleChange}
/>
</div>
<button type="submit" className="btn btn-primary">
Add group{" "}
</button>
</form>
<div>
<div key={group.id}>
{group.name} {group.admin}
</div>
</div>
</div>
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…