What is the best approach to create a dynamic value from axios response in a reactive object?

I am attempting to retrieve data from the backend (specifically the user role) and store it in a reactive container with Vue:

import {reactive} from "vue";
import axios from "axios";

export const store = reactive({

    auth: axios.get('/api/user').then(res => res.data.role),

})

Unfortunately, I am encountering issues. The data being fetched is in the form of a user object with a property called role which has a value of 1. Essentially, I want to capture this user role, save it globally and have it persist even when the window is refreshed. This would mean that store.auth is assigned as follows:

store.auth = 1

I understand that this could be achieved using sessionStorage or localStorage, but there are cases where direct fetching seems like a more appropriate approach.

I have already attempted the following methods:

auth: () => axios.get('/api/user').then(res => console.log(res.data.role))
auth: async () => axios.get('/api/user').then(res => console.log(res.data.role))
auth: async () => axios.get('/api/user').then(res => return res.data.role)
auth: return axios.get('/api/user').then(res => return res.data.role)

Answer №1

give this a shot

authorization: (await axios.get("/api/user")).data.role

Answer №2

Is the execution of the HTTP request included in this solution? It's important to clarify when and how this request should be triggered, rather than simply assigning it to a property.

To approach this more like a typical store setup, consider creating a function that is invoked as needed to fetch the required information. Without specific details on your use case, I'll demonstrate using onMounted to fetch data once when the component is initialized.

export const store = reactive({
    auth: 0,
})

onMounted(() => {
    axios.get('/api/user').then((res) => store.auth = res.data.role)
})

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

Initiate the execution of JavaScript functions in the loaded partial view using Ajax

I am currently working with a javaScript function that loads a partial view within my page's layout using the following logic: $('.follow-tasks').click(function (e) { e.preventDefault(); var $followtaskList = $("#td-" + $(this).attr ...

Is there a way to resolve the MongoDB Database-Differ Error?

I am currently working on creating an API and have set up a brand new Project, cluster, and Collection for it. However, when I attempt to use mongoose.save() to add data to my database, I keep receiving an error message. "message": { " ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

Unable to establish connection through MQTT 1884 protocol

Currently, my website's messaging system is powered by MQTT. While everything is functioning smoothly on my local machine, I encounter an error when trying to use the system on the production site: vendor.bbaf8c4….bundle.js:1 WebSocket connection ...

Steps to apply V-model to elements

I am currently facing an issue with giving dynamically created input fields dynamic v-models from JSON data using vue.js. Here's what I'm doing: new Vue({ el: '#app', data() { return { totalAmt: 500, paymentMode: ...

What is the process for reverting variables back to their original values using pure Javascript?

I am working on developing a hangman game using vanilla javascript and I need some assistance with resetting the game after a player loses. Specifically, I would like to: 1. Reset the "guessRemain" variable. 2. Clear out the "guess" id so that none of the ...

Array buffers are scheduled by BinaryJs and the Audio API

My node.js server is streaming some ArrayBuffers: var BinaryServer = require('binaryjs').BinaryServer; var fs = require('fs'); var server = BinaryServer({port: 2000}); server.on('connection', function(client){ var file = f ...

When is the right time to develop a new component?

Exploring the strategy behind determining when to create a new component in a web application using angularjs / angular has been on my mind lately. It seems like this concept could apply to all component-based front end frameworks as well. I understand th ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Problems encountered when trying to deploy on Firebase

I've been working on deploying my web app to Firebase, and I successfully ran the deploy script. However, when I try to access the URL, instead of seeing my app, I'm greeted with the Open Hosting Documentation page. Here is what my firebase.json ...

Adding CSS styling to a particular component within your Vue application using Vuetify JS

Imagine having a Test.vue file containing 2 v-text-field components. I'm looking to style only the first text field using CSS. Test.vue <template> <div class="test"> <v-text-field></v-text-field> <v-tex ...

The toast feature is struggling to locate its designated div

Hey there, I've encountered an issue where the toast alert doesn't display on the page after I log in, but it does show up when I sign out. Any thoughts on why this is happening? I've tried various things like logging the toastLiveExample an ...

Trouble with React Native ListView Item Visibility

I'm currently working on integrating the React Native <ListView /> component with the <List /> and <ListItem /> components from React Native Elements. However, I seem to be facing an issue where the <ListItem /> component is no ...

Enhance Your jQuery Experience with Advanced Option Customization

I am currently developing a plugin that deals with settings variables that can be quite deep, sometimes reaching 3-4 levels. Following the common jQuery Plugin pattern, I have implemented a simple method for users to update settings on the go using the not ...

Nested loops combined with a timeout occasionally results in failure

I encountered a problem with the loops and timeouts in my script that I created for practice. If you want to take a look at the script, you can find it here: http://codepen.io/JulienBarreira/pen/EWNoxJ When running the script, I noticed that sometimes one ...

I have managed to update the Immutable and Primitive Data-Types in JS. Now, the question arises - are these truly Primitives or are the concepts in

In JavaScript, there are 4 primitive data types that store values directly: String, Number, Boolean, and Symbol. I am excluding undefined and null from this list as they are special data types with unique characteristics. One key feature of primitives is ...

The form does not seem to be updating or refreshing even after an AJAX submission and validation

I have a form set up to submit data to my database using jQuery Validate plugin and ajax. However, I'm encountering an issue where after clicking submit, the form does not clear out. While the data does get updated in the database, I need help figurin ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

Reactjs Expressjs data display issueI'm experiencing difficulty with displaying

When I try to access the data using "dataUtilizador.Roles[0].name" after receiving a response from axios, the page goes blank. However, if I import the axios response and use "Record.Roles[0].name", it works fine. What am I doing wrong? import Record from ...

Why is it necessary to type in localhost in the address bar when using node.js and socket.io instead of simply opening the client.html file directly?

I am intrigued by this topic. My suspicion is that it may be related to the temporary file created by socket.io, but I'm struggling to fully understand it... ...