I press the onClick button and it sends the data (time and ID) to the backend.
The problem is: the backend receives the data twice instead of just one time. req.body prints the data twice. See at the bottom.
Does anyone know what am I doing wrong? When I console.log the post request, it prints only once. So, I assume the problem is somewhere in the code here.
const Shift = (props) => {
const [time, setTime] = useState();
const [inOut, setInOut] = useState('');
const getTime = (val) =>{
setTime(new Date().toLocaleString());
setInOut(val);
}
const displayMessage = () => {
switch(inOut) {
case 'in':
sendClockIn();
return <Card.Text>
Time: {time}<br/>You have clocked in ! <br/> Have a good working day!
</Card.Text>;
case 'out':
// sendClockOut();
return <Card.Text>
Time: {time}<br/>You have clocked out ! <br/>Enjoy the rest of the day!
</Card.Text>;
default:
return <Card.Text>
Choose one of the 2 options from above.
</Card.Text>;
}
}
const sendClockIn = async () => {
let id = props.Id;
let clock = time;
await ApiPostgres.dataSendClockIn({id, clock});
}
return (
<div>
<Card style={{ width: '25rem' }}>
<Card.Header>
<Button variant="primary" onClick={() => getTime('in')}>Clock In</Button>
</Card.Header>
<Card.Body>
{displayMessage()}
</Card.Body>
</Card>
</div>
);
};
export default Shift;
Backend:
console.log(req.body)
Gives me duplicate
{ id: 1, clock: '1/11/1111, 1:11:11 PM' }
{ id: 1, clock: '1/11/1111, 1:11:11 PM' }
Solution:
I removed sendClockIn() from displayMessage(). Then, I made a seecond switch statement in getTime(); Then, in sendClockIn() I created another to store the current time. It works as it should.
Does anyone know what is the difference? - Is it because displayMessage() renders on load and then when then onClick?
const getTime = (e, val) =>{
e.preventDefault();
setTime(new Date().toLocaleString());
setInOut(val);
switch('in') {
case 'in':
sendClockIn();
break;
default:
break;
}
}
const sendClockIn = async () => {
let id = props.Id;
let clock = new Date().toLocaleString();
await ApiPostgres.dataSendClockIn({id, clock});
}