-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?

2

1 Answer 1

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)
})
Sign up to request clarification or add additional context in comments.

1 Comment

You're absolutely right! Thanks so much. It makes more sense now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.