Search code examples
vue.jsdestructuringvue-composition-api

destructing api response in vuejs 3 composition api


how do I destructure the response to access results?

the code is

export default {
  setup() {
    const result = ref(null)

    onMounted(async ()  => {
      result.value = await axios.get('https://randomuser.me/api?results=50')
      const { result: {data: {results} } } = results.value
    })
    return { result }
  }
}

the response returned looks like enter image description here

the console error is "Cannot access 'results' before initialization"

thanks for any help


Solution

  • The response returned from axios.get() stores the data in its data property, so result.value.data contains the info and results fields.

    However, I think you're trying to store the results field in the result.value ref. You could store the API response in a temporary variable, and then destructure that:

    onMounted(async ()  => {
      const resp = await axios.get('https://randomuser.me/api?results=50')
      const { data: { results } } = resp
      result.value = results
    })
    

    demo