Skip to content
Advertisement

How to return variable from Axios Response in Composition API to root level?

I want to return the headings array from an axios.get function and use it on root level inside my vue component but when I try to return it, it shows:

ReferenceError: headings is not defined

This is the script element from my Vue3 Component:

<script setup>
import {ref} from 'vue';

const homePage = ref({
    heading: "",
    content: "",
    image: ""
});

axios.get('/home')
    .then(res => {
        const data = res.data[res.data.length - 1]
        const headings = {
            en: data['heading_(en)'],
            de: data['heading_(de)'],
            ar: data['heading_(ar)'],
        }
        return headings;
    })

console.log(headings);

</script>

Edit:

Thanks to Thomas and huan feng I can do this:

<script setup>
import {reactive} from 'vue';

const state = reactive({
    headings: {},
    content: {},
    image: ""
})

axios.get('/home')
    .then(res => {
        const data = res.data[res.data.length - 1]

        state.headings = {
            en: data['heading_(en)'],
            de: data['heading_(de)'],
            ar: data['heading_(ar)'],
        }

        console.log(state.headings.en)
    })

</script>

This is the most elegant solution because reactive objects provide the cleanest framework when working with arrays. Call it from the vue component like so:

    <h2>{{ state.headings.en }}</h2>

Since axios is asynchronous returning the variable into root level is more difficult and in my case not necessary. I can output it inside then.

Advertisement

Answer

// Better to wrap page states in a reactive object
const state = reactive({
    headings: []
})

axios.get('/home')
.then(res => {
    const data = res.data[res.data.length - 1]
    state.headings = {
        en: data['heading_(en)'],
        de: data['heading_(de)'],
        ar: data['heading_(ar)'],
    };
})
// Use state.headings before this line,
// Unpack it and you can directly use headings in template 
const {headings} = toRefs(state);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement