I'm trying to access an Object method outside the onMount, but I'm having an issue. I initialized the object inside the onMount, and I thought declaring the variable globally would solve the issue, but it didn't, so now I'm at a loss.
This is what I initially had. The code gave me an exception on slider.getInfo() saying that the object is possibly 'undefined.'
import { onMount } from "svelte";
import {tns} from "tiny-slider/src/tiny-slider.js";
let slider
onMount(()=>{
slider = tns({
container: ".my-slider",
slideBy: 1,
speed: 1000,
nav: false,
controls: false,
autoplay: true,
autoplayButtonOutput: false,
responsive: {
1024: {
items: 4,
}
},
})
})
let sliderInfo = slider.getInfo()
Next I tried putting it in a function and calling the function.
import { onMount } from "svelte";
import {tns} from "tiny-slider/src/tiny-slider.js";
let slider
onMount(()=>{
slider = tns({
container: ".my-slider",
slideBy: 1,
speed: 1000,
nav: false,
controls: false,
autoplay: true,
autoplayButtonOutput: false,
responsive: {
1024: {
items: 4,
}
},
})
})
function setInfo(){
let sliderInfo = slider.getInfo()
console.log(sliderInfo)
}
setInfo()
This time the code gave me the following error
Uncaught TypeError: Cannot read properties of undefined (reading 'getInfo')
Finally, just because I wanted to see if I could somehow get it to work, I created a button and assigned the function as a handler, and surprisingly this worked. Although I have no idea why this works compared to what I previously tried.
import { onMount } from "svelte";
import {tns} from "tiny-slider/src/tiny-slider.js";
let slider
onMount(()=>{
slider = tns({
container: ".my-slider",
slideBy: 1,
speed: 1000,
nav: false,
controls: false,
autoplay: true,
autoplayButtonOutput: false,
responsive: {
1024: {
items: 4,
}
},
})
})
function setInfo(){
let sliderInfo = slider.getInfo()
console.log(sliderInfo)
}
...
<button on:click={setInfo}>Click</button>
Unfortunately, the method that worked is not what I'm trying to do, but the first method instead. However I can't figure out why the first method doesn't work. Any help is appreciated.