I have two API calls I am making simultaneously based on an array of pets; I want to move to the next screen when they finish. The below code is what I currently have; I have to press the button twice for it to go to the next page.
API CALLS:
export default class CustomerInformationService {
getDataFromService = async (petId, type) => {
if (AppConstants.mockJson === true) {
return this.getMockData();
} else {
console.log("I AM REAL JSON");
return this.getRealData(petId, type);
}
};
getRealData = async (petId, type) => {
if (type === "EIP") {
return this.processEIPRequest(petId);
} else {
return this.processTMMRequest(petId);
}
};
First API Call
processEIPRequest = async (profileId) => {
const url = AppConstants.endpoint.patterns.getPetProfileInfo.path;
const params = new URLSearchParams([["ProfileId", profileId]]);
var response = null;
AppConstants.axiosEipGET.defaults.headers.common[
"Authorization"
] = `bearer ${token}`;
await AppConstants.axiosEipGET(url, { params })
.then((res) => {
console.log("RES", res);
response = res;
})
.catch((err) => {
if (err.response) {
console.log("ERROR", err.response.data);
response = err.response;
}
});
return response.data;
};
Second API Call
processTMMRequest = async (profileId) => {
const url = AppConstants.endpoint.patterns.editPetTMM.path "/" profileId;
console.log("URL :", url);
var response = null;
await AppConstants.axiosGET(url)
.then((res) => {
console.log("RES", res);
response = res;
})
.catch((err) => {
if (err.response) {
console.log("ERROR", err.response.data);
response = err.response;
}
});
return response.data;
};
}
Here is the portion that is calling the code.
invokeCustomer([{pets: "pet1", pets: "pet2"}])
function invokeCustomer(e) {
console.log("E: ",e)
e["pets"].forEach(pet => {
const petInitValues = {
petObj: {
"name": "",
"comments": ""
}
}
petInfoDataService.getDataFromService(pet["PETID"], "EIP").then(petData => {
console.log("PETs: ", petData["PetProfile"])
petInitValues.petObj.name = petData["PetProfile"].Name
petDataArray.push(petInitValues)
setHasPetData(true)
})
petInfoDataService.getDataFromService(pet["PETID"], "TMM").then(petInfo => {
console.log("PETs: ", petInfo)
petInitValues.petObj.comments = petInfo.comments
petDataArray.push(petInitValues)
setHasTMMPetData(true)
})
I set two setStates
in the then
of the response, but I have to press the button twice to go to the navigate portion.
if(hasPetData && hasTMMPetData) {
console.log("PET ARRAYS: ", petDataArray)
navigate("/CustomerInformation", { state: { CustomerInformation: e, hasPets: hasPets, petDataArray } });
}
})
}
CodePudding user response:
Maybe call the navigate portion inside useEffect
hook:
useEffect(() => {
if(hasPetData && hasTMMPetData) {
console.log("PET ARRAYS: ", petDataArray)
navigate("/CustomerInformation", { state: { CustomerInformation: e, hasPets: hasPets, petDataArray } });
}
}, [hasPetData, hasTMMPetData])
This will trigger the navigate portion as soon as both hasPetData
and hasTMMPetData
equals true