I have a JS code which is connected to ganache. I am trying to call a solidity function which in tern emit the event. In JS i am watching the event. Now when i call the function first time it sets some values in the event and emit. I get that value in watch. But when i call it second time, I get the previous logs which i printed in UI and the current value comes after some time. In my UI, i just need the current value which is set by the solidity function, i do not want the previous value. Looks like JS continuously polling the watch and in first pass it prints the old value and then finally it prints the current value. I want certain things to work only and only when the new values are sent by event. How do i do that. Let me know if you need more information or code to view.
Solidity Code :- Below solidity function emit the event.
function getStudent(string _searchHash) payable public {
var searchHash = _searchHash;
university.transfer(msg.value);
for(uint i=0; i<students.length; i++)
{
if (keccak256(students[i].hash) == keccak256(searchHash))
{
emit foundStudentInfo(students[i].fname, students[i].year,
university.balance);
}
}
emit foundStudentInfo("Failed","Failed",university.balance);
}
}
Below is my JS code to watch for an event:- what is happening here is, i am able to get the event data back. But it prints the data even before metamask comes up and i complete the transaction. Once the metamask transaction is complete it again prints the data. This time it prints the latest data which i want to get from solidity function. I precisely want to stop the loader when i get the current data. But in below code my loader stops before I receive the actual data. I want just want to display the current value which solidity function is finding based on the given input parameters. But I am getting all the previous data and do not know what is the correct time to print the data. I am new to this technology so not sure my expectation is right or I need to do some more changes.
async function temp (){
await Student.getStudent(hashCode, function(error, result){
if(!error)
{
console.log('result in callback' + result);
}
else
console.error(error);
});
} //async temp ends.
temp(); // calling temp.
async function getEvent() // function to watch event.
{
var studentEvent = await Student.foundStudentInfo();
eventData = await studentEvent.watch(function(error, result1){
if (!error)
{
if (result)
{
console.log(result1.args);
console.log(result1.blockHash);
$scope.loading = false;
$state.go('result');
}
else
{
console.log(error);
}
}
});
console.log('event data' ||eventData);
}
getEvent();