I’m a beginner in Livewire, need to display one of the templates (the first with a Resend button if $waitTime <=0 and the second if $waitTime >0) according to server event updateWaitTime . In the way I implemented it, wire:click=”getOTPCode(true)” doesn’t work. What is a proper way to implement it?:
<div class="d-flex justify-content-end"
x-data="otpSend()"
x-init="init()"
>
<template x-if="getTime() <= 0">
<button wire:click="getOTPCode(true)" type="button"
class="my-2 btn btn-primary rounded-pill text-white"><i
class="bi bi-arrow-counterclockwise"></i> Resend Code
</button>
<button hidden id="hide" data-bs-dismiss="modal"></button>
</template>
<template x-if="getTime() > 0">
<small>
Resend OTP in
<span x-text="formatTime(getTime())"></span>
</small>
</template>
</div>
<script>
document.addEventListener('livewire:load', function () {
window.livewire.on('submitted', function () {
resetForm();
focusForm();
})
window.livewire.on('resent', function () {
resetForm();
focusForm();
})
window.livewire.on('updateWaitTime', function (wait_before_resend) {
console.log(`updateWaitTime ${wait_before_resend}`);
otpSend(wait_before_resend);
})
window.livewire.on('success', function () {
setTimeout(() => {
$('#hide').click();
@this.emitSelf('reset')
;
}, 500)
})
})
function otpSend(waitTime) {
const milliseconds = waitTime * 1000 //60 seconds
const currentDate = Date.now() + milliseconds
var countDownTime = new Date(currentDate).getTime()
let interval;
return {
countDown: milliseconds,
countDownTimer: new Date(currentDate).getTime(),
intervalID: null,
init() {
if (!this.intervalID) {
this.intervalID = setInterval(() => {
this.countDown = this.countDownTimer - new Date().getTime();
}, 1000);
}
},
getTime() {
if (this.countDown < 0) {
this.clearTimer()
}
return this.countDown;
},
formatTime(num) {
var date = new Date(num);
return new Date(this.countDown).toLocaleTimeString(navigator.language, {
minute: '2-digit',
second: '2-digit'
});
},
clearTimer() {
clearInterval(this.intervalID);
}
}
}
</script>
<?php
public function getOTPCode($resend = false)
{
$this->emit('updateWaitTime', $this->wait_before_resend);
}
?>