I have a registerIntoQueue()
function that fills up an array with objects. Each object represents a person waiting in a queue to be served. The order of service is (FIFO), first in, first out. Find below my solidity code to add a person into the queue:
pragma solidity ^0.8.2;
uint peoplelBeforeMe = 0;
struct Queue {
address customerAddress;
uint peoplelBeforeMe;
uint256 arrivalTime;
}
Queue[] private serviceQueue;
function registerIntoQueue() public {
serviceQueue.push ( Queue(msg.sender, peoplelBeforeMe, block.timestamp ) );
peoplelBeforeMe++;
}
The code above, having registered three people, would generate the below array of objects:
[customerAddress:0x446..9702, peoplelBeforeMe:0, arrivalTime:1653884369]
[customerAddress:0x786..2009, peoplelBeforeMe:1, arrivalTime:1653884469]
[customerAddress:0x589..5454, peoplelBeforeMe:2, arrivalTime:1653884569]
Id like to bring your attention the value that the
peoplelBeforeMe
item in the object holds.
Following is the removeFromQueue()
function. The person who joined the queue first (represented by index[0]
) is always the one who gets served first and therefore gets removed from the serviceQueue array
. In my code, this is represented by serviceQueue.pop[]
as this removes the first item in the array, being in index[0]
.
Find below my removeFromQueue()
code:
function removeFromQueue() public {
for(uint i = 0; i < serviceQueue.length - 1; i++){
let numberOfPeopleBeforeMe = serviceQueue[i].peoplelBeforeMe;
serviceQueue[i].peoplelBeforeMe = numberOfPeopleBeforeMe - 1;
serviceQueue[i] = serviceQueue[i + 1];
}
serviceQueue.pop();
}
The ideal outcome when removeFromQueue()
is run would be:
[customerAddress:0x786..2009, peoplelBeforeMe:0, arrivalTime:1653884469]
[customerAddress:0x589..5454, peoplelBeforeMe:1, arrivalTime:1653884569]
Kindly note how the
peoplelBeforeMe
was updated
My code in Remix, compiles perfectly well, and I am able to deploy it to the Ganache as a provider. The issue is, when I run the Dapp in the UI/front end I get the following error message:
It took me a while to figure out that commenting out
or removing the follwing code from the removeFromQueue()
function, resolves the issue:
let numberOfPeopleBeforeMe = serviceQueue[i].peoplelBeforeMe;
serviceQueue[i].peoplelBeforeMe = numberOfPeopleBeforeMe - 1;
making it:
function removeFromQueue() public {
for(uint i = 0; i < serviceQueue.length - 1; i++){
serviceQueue[i] = serviceQueue[i + 1];
}
serviceQueue.pop();
}
The code above erronously yeilds:
[customerAddress:0x786..2009, peoplelBeforeMe:1, arrivalTime:1653884469]
[customerAddress:0x589..5454, peoplelBeforeMe:2, arrivalTime:1653884569]
...because the peoplelBeforeMe
doesn't reflect the number of people before each person in the queue.
How do I correctly update the peoplelBeforeMe
item without it causing any issues and with minimum gasfees?