Reputation: 1
I made a widget using alpine js however, getting an error like and finding solution to my research. What do you think is the error in my code? When I pull the data, the header part is said to be incorrect. But I can't see a problem. Or I couldn't figure it out.
[Errors i see in console][1] [1]: https://i.sstatic.net/ofmW1.png
<div class="text-base w-56 px-5 rounded-full overflow-hidden" x-data="{
textArray: [],
text: '',
textIndex: 0,
charIndex: 0,
pauseEnd: 2750,
cursorSpeed: 420,
pauseStart: 20,
typeSpeed: 50,
direction: 'forward'
}" x-init="(() => {
fetch('/wp-json/wp/v2/pages/219/?_fields=acf.positions&acf_format=standard')
.then(response => response.json())
.then(data => textArray = data.acf.positions );
let typingInterval = setInterval(startTyping, $data.typeSpeed);
function startTyping(){
let current = $data.textArray[$data.textIndex].title;
if($data.charIndex > current.length){
$data.direction = 'backward';
clearInterval(typingInterval);
setTimeout(function(){
typingInterval = setInterval(startTyping, $data.typeSpeed);
}, $data.pauseEnd);
}
$data.text = current.substring(0, $data.charIndex);
if($data.direction == 'forward'){
$data.charIndex += 1;
} else {
if($data.charIndex == 0){
$data.direction = 'forward';
clearInterval(typingInterval);
setTimeout(function(){
$data.textIndex += 1;
if($data.textIndex >= $data.textArray.length){
$data.textIndex = 0;
}
typingInterval = setInterval(startTyping, $data.typeSpeed);
}, $data.pauseStart);
}
$data.charIndex -= 1;
}
}
setInterval(function(){
if($refs.cursor.classList.contains('hidden')){
$refs.cursor.classList.remove('hidden');
} else {
$refs.cursor.classList.add('hidden');
}
}, $data.cursorSpeed);
})()">
<span x-text="text"></span>
<span class="opacity-70" x-ref="cursor">|</span>
</div>
Thanks in advance for your suggestions and help.
Upvotes: 0
Views: 923
Reputation: 629
It's complaining that $data.textArray[$data.textIndex]
is undefined, and you're trying to read .title
from it.
when you first load your widget you do a fetch to populate textArray
, but until that returns your textArray
is empty so when you're trying to call let current = $data.textArray[$data.textIndex].title
it's returning the error
You basically need to ensure textArray has data before you try to access it:
.then(data => textArray = data.acf.positions );
so it's only started when the fetch has been called.if (textArray.length === 0) return;
line at the start of your startTyping
function so it doesn't try to do anything until textArray is populatedmight not be your only issue, but this is the cause of the error you've posted
Upvotes: 1