Issue
Can anyone tell me, why in the code below, in the return block, this
stays undefined
?
export const useAutoSave = (
cacheKey: string,
interval: number,
getSaveData: () => Omit<SaveDto, 'savedTime'>,
) => {
let timer: any
const { storage, reset } = useStorageObject<SaveDto>(
SaveDto,
'auto-save-' + cacheKey,
false,
)
const save = () => {
// ...
}
return {
reset,
getPrevSaved() {
return storage
},
save,
track() {
console.log(this) // <-- why is `this` `undefined` here?
this.disposer() // <-- reference error
timer = setInterval(save, interval)
},
disposer() {
clearInterval(timer)
},
}
}
Solution
Assuming that function is in a module, this
is automatically bound to undefined
by Babel, leading to the errors you observed.
To get your code to work, disposer
needs to be declared beforehand (like you've done with save()
):
export const useAutoSave = (
cacheKey: string,
interval: number,
getSaveData: () => Omit<SaveDto, 'savedTime'>,
) => {
let timer: any
const disposer = () => {
clearInterval(timer)
}
return {
//...
track() {
disposer()
timer = setInterval(save, interval)
},
disposer,
}
}
Answered By - tony19
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.