fixed code to make query only sent after data is retrieved