-1

I have a "composable" axios function like this

export const useFetch = (url: string, config: any = {}) => {
  const data = ref(null)
  const status = ref()
  const error = ref(null)
  const loading = ref(false)
  const fetch = async () => {
    loading.value = true
    error.value = null
    try {
      const result = await service.request({
        url,
        ...config
      })
      status.value = result.status
      data.value = result.data
    } catch (ex) {
      error.value = ex
    } finally {
      loading.value = false
    }
  }
  fetch()
  return { status, error, data, loading }
}

In a separate file like user.vue, I call useFetch like this

  setup() {
    const { data, error } = useFetch(
      'https://jsonplaceholder.typicode.com/po3sts/1',
      {
        method: 'get'
      }
    )
    console.error(error)
    console.error(error.value)
    return { data, error }
  }

My problem is when I console.error(error), I can clearly see

Object { value: Getter & Setter }
value: Error: Request failed with status code 404

But if I do console.error(error.value), it returns null.

Any tips on how to get error.value?

  • Does this answer your question? [console log event object shows different object properties than it should have](https://stackoverflow.com/questions/26496176/console-log-event-object-shows-different-object-properties-than-it-should-have) – Michal Levý Jul 22 '21 at 07:03
  • See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?rq=1 – Estus Flask Jul 22 '21 at 07:24

1 Answers1

0

console.error(error.value) outputs the actual value at this moment of time, while console.error(error) passes the object by reference to console and allows to access updated object properties later, this is the use case what ref pattern addresses.

useFetch is asynchronous and the result isn't supposed to be instantly available. With composition API, the result is supposed to be accessed as:

watch(loading, loadingValue => {
  if (!loadingValue)
    console.error(error.value)
})

Alternatively, the hook can be modified to return a promise that could be chained, this is orthogonal to composition API but has its uses to compose hook results with promise control flow:

  ...
  const promise = fetch()
  return { status, error, data, loading, promise }
  ...

and

onMounted(async () => {
  await promise
  console.error(error.value)
})
Estus Flask
  • 206,104
  • 70
  • 425
  • 565