another approach for fixing the race condition. moved data listener to the end of the function