I’m trying to post a request, then receive its response data to then post other request:
const [groupId, setGroupId] = useState();
const handleFormSubmit = () => {
e.preventDefault()
axios.post('https://localhost:7028/group', someDemoData)
.then((response) => {
setGroupId(response.data)
})
.catch((error) => { console.log(error); })
createParticipant(groupId);
}
So what I was trying to do here is create a group with someDemoData, then setGroupId with the response data received, then pass groupId to createParticipant(). To make it easy, for now, inside createParticipant will only have console.log(“groupId: ” + groupId). The result I got is undefined.
I do understand the reason is when I called setGroupId, react will not set it immediately, nor waiting for it to complete then to do later actions (async), so when createParticipant(groupId) get called, groupId hasn’t been set yet and that why I got undefined as result.
I searched for some similar question and people keep saying use useEffect. But here I wanna wait for it to update in my handleFormSubmit(), so I can use the response data to pass to createParticipant().
So how can I wait for groupId to set?