I'm trying to fetch data from the backend (user role) and assign it to a reactive store
:
import {reactive} from "vue";
import axios from "axios";
export const store = reactive({
auth: axios.get('/api/user').then(res => res.data.role),
})
but it doesn't work. The fetched object
is a user object
with a role
property that is 1
. Basically I want to detect user.role
, store it and make it globally available whenever the window is refreshed. This means that store.auth
is set like this:
store.auth = 1
I know that it is possible with sessionStorage/localStorage
but fetching it directly might be the better approach in some situations.
I've tried:
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)
CodePudding user response:
try this
auth:(await axios.get("/api/user")).data.role
CodePudding user response:
Does this solution actually attempt the HTTP request? We need to provide some context around when that request should be made, it can't just be assigned to a property.
If you want to treat this as a more traditional store, then you could define a function that is called as an action when you need this information. Lacking information on how you want to use this, I'll give an example using onMounted, which will populate this data once when the component is loaded.
export const store = reactive({
auth: 0,
})
onMounted(() => {
axios.get('/api/user').then((res) => store.auth = res.data.role)
})