Is it possible to pass a variable from an Axios Response in the Composition API up to the root level?

I need to fetch the headings array from an axios.get call and utilize it at the root level within my Vue component. However, when I attempt to return it, I encounter this error:

ReferenceError: headings is not defined

Here is the script element in 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:

Credit goes to Thomas and huan feng for helping me arrive at this solution:

<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 approach is considered the most elegant because reactive objects offer a cleaner structure when working with arrays. Use it in the Vue component like this:

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

Due to the asynchronous nature of axios, retrieving the variable at the root level proves to be more challenging and unnecessary in my scenario. Displaying it within the then block suffices.

Answer №1

// It is more efficient to encapsulate page states in a reactive object
const state = reactive({
    titles: []
})

axios.get('/landing')
.then(res => {
    const result = res.data[res.data.length - 1]
    state.titles = {
        english: result['title_(en)'],
        german: result['title_(de)'],
        arabic: result['title_(ar)'],
    };
})
// Access state.titles before reaching this point,
// Deconstruct it and directly utilize titles in the template
const {titles} = toRefs(state);

Answer №2

Building upon my previous input:

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

const landingPage = reactive({
    titles: {},
    description: '',
    picture: ''
});

axios.get('/landing')
    .then(response => {
        const info = response.data[response.data.length - 1]
        landingPage.titles = {
            english: info['title_(en)'],
            german: info['title_(de)'],
            arabic: info['title_(ar)'],
        }
    })

</script>

Additionally, I recommend utilizing the reactive feature for managing objects.

UPDATE: Syncing the retrieved data with the landingPage reactive object.

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

You can submit a photo to a form as an attached file

I had a code that looked like this My goal is to simplify the process for users by allowing them to fill out additional information in a form without having to upload an image separately. I want to display the canvas image from the previous page in the fo ...

Revolutionary Approach to Efficiently Handle Multiple rows with Jquery

Greetings to everyone, I am currently in the process of developing an application that retrieves data from a database via AJAX by calling a .php file. Within this app, I have a table with 4 columns. The first two columns consist of dropdown menus, the thi ...

Webpack compatibility issue hindering big.js node module functionality

I'm currently working on compiling (typescript files) and bundling my source code using webpack. Below is the content of my webpack.config.js file: const path = require('path') module.exports = { devtool: 'eval-source-map', en ...

Error in Firefox when converting a string to a date in JavaScript using the format mm-dd-yyyy

Hi, I am encountering an issue with converting a string in the format mm-dd-yyyy into a date object. While it works perfectly fine in Internet Explorer and Chrome, it does not work in Firefox as it returns an invalid date at times. I have also tried using ...

Verification of the data entered in the input box

I am looking to develop an Input Box where users can enter the private details of a person. The first character must be either A or E, and the rest can be alphanumeric with no special characters allowed. I need to implement validation on the client side to ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

Is it possible to transfer an HTML table to a PowerPoint presentation directly from the client

Is there a specific jquery or javascript solution available for converting an HTML table directly into a PowerPoint presentation? So far, the only solution I have come across is html table export, which provides export options for various file formats. H ...

What techniques can be used to avoid blinking while forcefully scrolling to the left?

In my previous inquiry about dynamically adding and removing divs on scroll, I was unable to find a satisfactory solution among the responses provided. However, I decided to take matters into my own hands and attempted to implement it myself. My approach ...

Vuetify alters the text color of the <vs-button> element

Outline of the Issue Upon installing vuetify, the text color of my <vs-button> has changed from white to black. Despite trying to adjust the color in the vuetify theme, I am unable to change it back. I have also created a custom filter rule using po ...

Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where ...

The loading GIF in jQuery is malfunctioning when displayed simultaneously on multiple div elements

I am currently working on my Laravel dashboard's blade to showcase various statistics. These stats will be updated whenever the date picker is changed. Below is the code for my date picker: <div class="row"> <div class=&qu ...

Guide on sending a key to a text input field using JavaScript

How can I simulate sending a combination of keys (such as Ctrl+C or Alt+Shift) when the cursor enters an input text field using Javascript? I am not utilizing jQuery, but rather MS-Ajax. Is it achievable with MS-Ajax DOM? EDIT 1) Following @Ghostoy&apos ...

Angular Bootstrap-Select: Displaying options even after selection

There seems to be a bug in the angular bootstrap select demo section. After selecting an option, the dropdown continues to display options instead of hiding them. This issue does not occur when the ng-model attribute is omitted. You can view an EXAMPLE he ...

Host an Angular app with views using Express.js - reloading is disabled

I'm currently working with an expressjs configuration that looks like this: app.use(express.static(path.join(__dirname,"../../site"))); app.use("/src", express.static(path.join(__dirname,"../cms/src"))); app.get('/', function(req, res){ ...

Tips for adjusting the font size of a Chip using Material-UI

I am using a widget called Chip const styles = { root:{ }, chip:{ margin: "2px", padding: "2px" } } const SmartTagChip = (props) =>{ const classes = useStyles(); return( <Chip style={{color:"white&q ...

What causes Angular to redirect to the route but display the incorrect view?

There is a fundamental issue I have encountered while working with routes: I have multiple routes defined If the user is not authenticated, they are redirected to the login page The problem lies in the fact that, on the initial display of the web app, t ...

I am sending an AJAX request to a remote server in order to retrieve access records

Currently, I am attempting to retrieve data by sending an ajax request to a remote server controller from my current remote page. Below is the code for my first remote view page: <?php include 'header.php'; ?> <script src="/assets/js/ ...

Easy Registration Page using HTML, CSS, and JavaScript

In the process of creating a basic login form using HTML and CSS, I'm incorporating Javascript to handle empty field validations. To view my current progress, you can find my code on jsfiddle My goal is to implement validation for empty text fields ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...

What is the best way to dynamically set the `to` prop in nuxt-link?

I have been struggling with this issue for quite some time now. In my basic Nuxt project, the directory structure is set up as shown below (please ignore the fun.vue): https://i.sstatic.net/hKDpb.png The goal is to allow navigation to individual posts us ...