Home > Net >  why Im failing to access axios.get() data once I pass it to a reactive object vuejs?
why Im failing to access axios.get() data once I pass it to a reactive object vuejs?

Time:07-02

I'm quite new with Vue and what I'm doing is really simple, must be some reactivity issue I think, the thing is that I'm doing an axios.get(), and when I console.log(res.data) it shows all ok. But when I try to make the res.data = reactive object it just logs this ⇾ Proxy {} (like there's nothing in it) I leave the code and 2 pictures, once for every scenario. Code when console.log res.data and it's ok:

<script>
import { onMounted, reactive, ref } from 'vue';
import axios from 'axios';

export default {
  name: 'HomeView',
  setup() {

    const state = reactive({
      destinations: []
    })

    const destinations = ref([]);

  onMounted( () => {
      axios.get('https://my-json-server.typicode.com/Tommydemian/vue-school-router/db')
      .then(response => response.data.destinations)
      .then( data => console.log(data) )
  }) 
    return {
      state
    }
  }
}
</script>

Here's the response: enter image description here

and here is the change in the code and the image from console.log:

const state = reactive({
      destinations: []
    })

  onMounted( () => {
      axios.get('https://my-json-server.typicode.com/Tommydemian/vue-school-router/db')
      .then(response => response.data.destinations)
      .then( data => (state.destinations = data) )
  })
    console.log(state.destinations)

img: enter image description here

CodePudding user response:

you aren't assigning the value of the axios response to the state, try it:

onMounted(async () => {
  const response = await axios.get(
    "https://my-json-server.typicode.com/Tommydemian/vue-school-router/db"
  );
  state.destinations = response.data.destinations;
});

Note: The console.log under the onMounted show the state empty because is async and the console.log run before that function.

Check the sandbox here

  • Related