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

Time:10-26

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.

CodePudding user response:

// 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);

CodePudding user response:

Expanding on my comment:

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

const homePage = reactive({
    headings: {},
    content: '',
    image: ''
});

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

</script>

And I suggest using reactive for objects.

EDIT: applying the response to the homePage reactive object.

  • Related