user10965730
user10965730

Reputation: 97

In Vue 3 hook, in the return type object inside `this` is always `undefined`

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)
    },
  }
}


Upvotes: 0

Views: 234

Answers (2)

Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18618

Please refer to functional components migration guide and Vue 3 functional components documentation.

You should pass props and context as arguments to the functional component.

const FunctionalComponent = (props, context) => {
  // ...
}

Upvotes: 0

tony19
tony19

Reputation: 138476

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,
  }
}

Upvotes: 3

Related Questions