Home > OS >  Vuejs3 Axios Express - Display data from array/object
Vuejs3 Axios Express - Display data from array/object

Time:10-25

I am trying to output a single post from an express API using Vue.

Problem is that the object/array returned (post.value) does not display the values that I declare in the template (post.title & post.body).

Any help would be greatly appreciated.

<template>
<div v-if="post">
    <h2>{{ post.title }}</h2>
    <p>{{ post.body }}</p>
</div>
</template>

<script>
import axios from 'axios'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

export default {
    name: 'BlogPostView',
    setup() {
        const post = ref([])
        const route = useRoute()
        const error = ref('')

        const load = async (id) => {
            
            try {
                await axios.get(`http://localhost:5000/api/posts/${id}`)
                    .then((response) => {
                        post.value = response.data
                        console.log(post.value)
                        console.log(response.data)   
                    })
            } catch(err) {
                error.value = err.message
            }            
        }

        load(route.params.id)

        return { post, error }
    }
}
</script>

Just for reference:

console.log(params.value) got no errors, and outputs the following:

Proxy {0: {…}}[[Handler]]: Object[[Target]]: Array(1)[[IsRevoked]]: false

UPDATE I was able to output the variables, but with the help of a v-for loop. Just wondering if there's another way to output it without using a loop. I was able to make it work using Vue firebase, but not on this stack.

CodePudding user response:

Since your API is returning an array with one post, you can just store the post without the array around it.

<template>
<div v-if="post">
    <h2>{{ post.title }}</h2>
    <p>{{ post.body }}</p>
</div>
</template>

<script>
import axios from 'axios'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

export default {
    name: 'BlogPostView',
    setup() {
        const post = ref({}) // make this an object
        const route = useRoute()
        const error = ref('')

        const load = async (id) => {
            
            try {
                const response = await axios.get(`http://localhost:5000/api/posts/${id}`)
                post.value = response.data[0] // Get the first item from the array
                console.log(post.value)
                console.log(response.data) 
            } catch(err) {
                error.value = err.message
            }            
        }

        load(route.params.id)

        return { post, error }
    }
}
</script>

  • Related