How to utilize Vue.js 3, Axios, and Express to showcase data retrieved from an array or

Trying to display a single post fetched from an express API using Vue has been challenging.

The issue lies in the fact that the values declared in the template for post.title & post.body are not being displayed as expected when accessing post.value.

If anyone could offer some assistance, it 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>

For your information:

While console.log(params.value) does not show any errors and displays the following:

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

UPDATE Although I managed to output the variables using a v-for loop, I am curious if there is an alternative method to achieve this without a loop. I was successful with Vue + firebase, but facing challenges on this particular stack.

Answer №1

If the API returns an array containing a single post, it's unnecessary to store the post within the array.

<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({}) // Change to 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] // Retrieve first item only
                console.log(post.value)
                console.log(response.data) 
            } catch(err) {
                error.value = err.message
            }            
        }

        load(route.params.id)

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to generate JSON data in a plain text format rather than using HTML

I have a snippet of code that retrieves the user's location every 5 seconds. <div id="geo" onLoad=""></div> <script> function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPo ...

Dynamic jQuery URL truncater

Is there an on-the-fly URL shortener similar to Tweetdeck available? I have come across several jQuery and JavaScript plugins that can shorten a URL through services like bit.ly when a button is clicked. However, I am looking for one that shortens URLs aut ...

When conducting tests using Selenium and the headless Google Chrome browser in Java, the dynamic JS content fails to load

Currently, I am in the process of testing a website that I have developed as part of a Spring Boot project using Selenium. While I can successfully test basic functionalities such as page loading and title verification, I am encountering difficulties when ...

Express-Postgres encounters an issue with applying array filtering: error message indicates that the operator for comparing integer arrays and text arrays does not exist

I'm facing an issue where the same query that works on the terminal is now giving me an error: operator does not exist: integer[] && text[] It seems that pg.query is having trouble processing the expression path && Array[$1]. You can ...

Calculate a new value based on input from a dynamic textbox within a datatable when a key is pressed

This question is a follow-up from the following solved queries (please do not mark it as a duplicate): jquery: accessing textbox value in a datatable How to bind events on dynamically created elements? I have generated a dynamic textbox within a dat ...

Is it possible to modify POST data before redirecting using expressjs?

Here is the basic code structure that I have: // in file1.php <?php print_r($_POST); ?> <form method="POST" action="http://localhost:1234"> <button type="submit" value="3" name="q">Register</button> </form> // in ser ...

AngularJS ui-router resolve function may not successfully return a custom value

While attempting to preprocess some data before navigating to my page, I am forcefully resolving a promise, converting it into a custom object, and then trying to return the custom object to my resolve object. .state("trip.detail", { ...

The jade code is causing an error to be displayed

The following Jade code seems to be malfunctioning. head script(src='http://d3js.org/d3.v3.min.js') script(src='http://dimplejs.org/dist/dimple.v2.1.0.min.js') body script(type='text/javascript') var svg ...

Implementing a responsive grid layout using a map function with ReactJS and Bootstrap

Upon receiving data from the backend, my goal is to display the data in a bootstrap grid. However, in ReactJS, you cannot delay closing a div until a certain number of occurrences. Below is an example of the code illustrating my issue. export default cl ...

Unable to establish a connection between Node.js and RabbitMQ within a docker container

I am currently attempting to establish a connection between an Express app and RabbitMQ in a docker container. The operating system I am working with is Windows 10, and only RabbitMQ has been dockerized. Below is the content of the docker-compose file: ve ...

Retrieve the values of all child attributes in the XML file

This is a sample XML structure: <child_2 entity_id="2" value="Root" parent_id="1"> <child_4 entity_id="4" value="Activities" parent_id="2"> <child_10066 entity_id="10066" value="Physical1" parent_id="4"> <child ...

Fresh ajax requests are not clearing the current data displayed in the JSP table

My ajax function retrieves data from a servlet and displays it in the page successfully. However, each time a new ajax call is made, the form appends the new data to the existing results instead of replacing them. I need to reset the current values stored ...

My goal is to utilize React JS to generate a table by sending the values through props using an array of objects

I have experience building tables as part of various projects, but I am facing challenges creating a table based on the provided format for this specific project. My goal is to utilize the RecordTable Component, render the table component, pass the row com ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

Utilize the Google Maps API to align an SVG symbol with the direction of an aircraft's

I have been struggling to update the rotation of the Google Maps API SVG aircraft symbol to display the correct heading as it moves. Although it initially loads with the correct heading, I can't seem to figure out how to dynamically update it. I' ...

Looking for assistance in using JavaScript to determine the percentage of a DIV's width in pixels

Using PHP, I am generating boxes whose width is set to 100% of a container in CSS. Now, I want to determine the equivalent pixel value of that box... HTML <div class="masonry" > <? while($row = $stmt->fetch()){ ?> <div class="i ...

Unlock the power of nested dynamic content creation with JavaScript

Every time I attempt to use getelementbyid on a dynamically loaded div, I receive null as the result. This occurs even after trying both window.onload = function () { and $(window).load(function() { index.html: <main > <div id="main-div"> ...

Iterate over Observable data, add to an array, and showcase all outcomes from the array in typescript

Is there a way to iterate through the data I've subscribed to as an Observable, store it in an array, and then display the entire dataset from the array rather than just page by page? Currently, my code only shows data from each individual "page" but ...

What could be causing my component to not update after I modify the states?

When I make an ajax request and update the state with the response data, my list of items does not rerender as expected. Even though the state is updated successfully, the changes are not reflected in the UI. export class Tiles extends React.Component { ...

When using npm install with a forked library, the installation may not be fully completed

Currently, I am working on a private Node.js project developed using Nest.js. For this project, I am utilizing the node-coap library, which I have forked into our company's GitHub profile. However, when I try to install it into the project using npm i ...