0

I have a problem with a simple function, I'm not understanding where is the problem. I'm working on Vue.

setup(props) {
    console.log('sono setup')
    const state = reactive({
      myMenu5: [],
      myMenuTry: [
        {
          title: 'Home',
          route: 'home',
          icon: 'HomeIcon',
        },
        {
          title: 'Second Page',
          route: 'second-page',
          icon: 'FileIcon',
        },
      ],
    })
    onMounted(() => {
      console.log('sono su onMounted')
      async function getMenu() {
        await axios.get('https://jsonplaceholder.typicode.com/posts').then(res => {
          state.myMenu5.push(JSON.parse(JSON.stringify(res.data)))
          console.log('res1', res.data)
        }).catch(err => console.log(err))
      }
      getMenu()
      // state.myMenu5 = JSON.parse(JSON.stringify(state.myMenu5))
      console.log('myMenu5', state.myMenu5)
      const ciao = JSON.parse(JSON.stringify(state.myMenu5))
      console.log('ciao', ciao)
    })

This is my component and my reactive myMenu5 when I populate inside the function getMenu give me this result:

myMenu5 [__ob__: Observer]
0: (100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
length: 1
__ob__: Observer {value: Array(1), dep: Dep, vmCount: 0}
__proto__: Array

How to convert to Array? I'm blocked here. I searched to other posts but every solution not worked for me. Thank you

Alberto Torrisi
  • 85
  • 1
  • 10
  • 2
    Does this `JSON.parse(JSON.stringify(state.myMenu5))` not return an array for you? – Chris Kao Jun 09 '21 at 09:03
  • Return an observer. For now i have not a problem, because component props don't give me an error. thank you bro – Alberto Torrisi Jun 09 '21 at 09:25
  • You seem to be looking for `state.myMenu5 = res.data` or `state.myMenu5.push(...res.data)` instead of `state.myMenu5.push(res.data)`. – Bergi Jun 09 '21 at 10:28
  • 1
    You cannot convert an observer to an array, and you don't need to. It's not an observer, it already *is* an array - even if it's an *observable* array, it's still an array. But your real issue appears to be that you attempt to log the value before the `getMenu` function has completed the asynchronous http request. – Bergi Jun 09 '21 at 10:31

0 Answers0