1

I encountered axios error in the process of creating my application.

The below code work fine. in the first image,console.log output res.data.

let categoryId = ''

axios.get('/api/max')
    .then((res) => {
        console.log(res.data) // image part
        categoryId = res.data.id
    })
    .catch((err) => {
        console.log('ssssssuuuuu')

    })

('api/max') return category with max ID.

enter image description here

The below code don't work well. console.log(res) output properly, but console.log(res.data) output undefined.

try {
    const res = axios.get('/api/max')
    console.log(res)
    console.log(res.data) // undefined
    categoryId = res.data.id
    console.log('a')
} catch (err) {
    console.log(err.message)
}

enter image description here

what causes undefined? I googled but, I didn't know the cause.

I'm sorry that my English is not very good. Thank you for your help.

Phil
  • 157,677
  • 23
  • 242
  • 245
sora sakamoto
  • 83
  • 1
  • 8
  • What do you have around your `try catch` ? Try to wrap it into an `async` and use `await` in front of your axios get. – kissu Nov 21 '22 at 23:37

1 Answers1

0

You should use await axios.get('/api/max') before using console.log since it's an async call. (you can also use .then but it's less friendly)
Of course, don't forget to wrap your function into an async when using await.

Also, keep in mind that quirk when using console.log. Prefer using Vue devtools to inspect the current state you do have on your page.

Overall, I recommend the usage of async/await over .then all the time.
Here is a nice documentation for that one: https://javascript.info/async-await

kissu
  • 40,416
  • 14
  • 65
  • 133
  • 1
    sorry for replying so late. I did what you say and works well. I completely thought that await keyword in front of axios is unnecessary when substituting a value for a variable. thank you for your help! – sora sakamoto Nov 22 '22 at 05:13
  • @sorasakamoto did my answer solved your issue? – kissu Nov 22 '22 at 08:28
  • 1
    Yes! and I learned that I need to read thoroughly promise document. Thank you for your help! – sora sakamoto Nov 22 '22 at 12:38