I have 2 API calls on a page, and I need to trigger an event on useEffect, only if information from both APIs are exist.
transaction
object from the first API. paymentData
from second API
useEffect(() => {
if (transaction?.transId && paymentData) {
EventTracker.purchase({
...transaction.transId,
vendor: getVendorType(paymentData.vdType),
});
}
}, [transaction?.transId, paymentData]);
This results in 2 events being sent since I have 2 dependencies [transaction?.transId, paymentData]
and UseEffect executes on both.
Rather I want to restrict the event to be sent only one time if both transaction and paymentData
exists.
How do I achieve it? can I use dependencies like [transaction?.transId && paymentData]
2
Answers
You can use multiple dependencies as they change, useeffect will trigger. Your code should work.
But why dont you use promises in this case. Use Promise.all method for both apis and perform you action once they get resolved.
[transaction?.transId && paymentData]
should work in your case.By using
[transaction?.transId && paymentData]
as the dependency, theuseEffect
will only be triggered when the condition evaluates to true, i.e., when bothtransaction?.transId
andpaymentData
exist.