Vue: Pinia state property doesn't update in component with node-forge - vue.js

I read the other stackoverflow questions but does not help. I use pinia=2.0.27. I could extend the example if neccessary.
I have a component with a button with a spinner.
<template>
....
<button
type="submit"
class="btn btn-primary"
:disabled="loading ? true : false"
#click="submitForm"
>
<span
v-show="loading"
class="spinner-border spinner-border-sm"
role="status"
aria-hidden="true"
/>
<span v-show="loading"> Wait </span>
<span v-show="!loading">
Create certificate
</span>
</button>
....
</template>
<script setup>
import { storeToRefs } from "pinia";
import { useUserStore } from "#/store/UserStore";
const { loading } = storeToRefs(useUserStore());
</script>
<script>
export default {
async submitForm() {
try {
await useUserStore().createCertificate();
} catch (error) {
console.log(error);
}
},
};
</script>
This is the pinia store:
import { defineStore } from "pinia";
import forge from "node-forge";
export const useUserStore = defineStore({
id: "UserStore",
state: () => {
return {
loading: false,
};
},
actions: {
async createCertificate() {
this.loading = true;
try {
const keys = forge.pki.rsa.generateKeyPair(2048);
} catch (error) {
console.log(error);
} finally {
this.loading = false;
}
},
},
});
The problem is, that the doStuff function already runs and the loading property is still false inside the component and the spinner is very late visible.

Related

Vue.js Composition API vs Options API - posts ref in a v-for loop

I'm still new to VueJS, and I cannot figure this one out.
I have a page that loads with axios from wordpress my posts:
export default {
data() {
return {
postsUrl: "https://localhost/wordpress/wp-json/wp/v2/news",
posts: [] as any[],
isLoading: false,
regex: /(<([^>]+)>)/gi,
errorCaught: false,
};
},
methods: {
getPosts() {
this.isLoading = true;
axios
.get(this.postsUrl, { params: { _embed: true } })
.then((response) => {
this.posts = response.data;
console.log("Pages retrieved!");
console.log(this.posts);
this.isLoading = false;
})
.catch((error) => {
console.log(error);
if (error) {
this.isLoading = false;
setTimeout(() => {
this.errorCaught = true;
}, 1100);
}
});
},
},
mounted() {
this.getPosts();
},
};
and the template
<template>
<div class="news-container">
<div class="loading">
<transition name="fadeLoading">
<div v-if="isLoading">Loading...</div>
</transition>
<transition name="fadeLoading">
<div v-if="errorCaught">There was an error loading news</div>
</transition>
</div>
<ul v-for="(index) in posts" :key="index" ref="posts">
<h1>
<router-link :to="index.slug" tag="div" key="page.id"
>{{ index.title.rendered }}
</router-link>
</h1>
<img
v-if="index._embedded['wp:featuredmedia']"
:src="index._embedded['wp:featuredmedia'][0].source_url"
/>
<p class="date">{{ index.date }}</p>
</ul>
</div>
</template>
This works fine, no problem with the Options API.
But when I want to convert this to the Composition API, the posts don't appear:
<script setup lang="ts">
import axios from "axios";
import { ref } from "vue";
import { onMounted } from "vue";
const postsUrl = "https://localhost/wordpress/wp-json/wp/v2/news";
var posts = ref([] as any);
const isLoading = ref(false);
const regex = /(<([^>]+)>)/gi;
const errorCaught = ref(false);
const getPosts = () => {
isLoading.value = true;
axios
.get(postsUrl, { params: { _embed: true, page: 1 } })
.then((response) => {
posts = response.data;
console.log("Pages retrieved!");
console.log(posts);
isLoading.value = false;
})
.catch((error) => {
console.log(error);
if (error) {
errorCaught.value = true;
}
});
};
onMounted(() => {
getPosts();
});
</script>
I suspect there is a misunderstanding on my part how refs work, because If I edit the <template> (and have npm run dev running the server), I can see that the posts appear.
Could you help me with what am I doing wrong and why?
Thank you for your time
Your mistake is here
posts = response.data;
When you use ref you have to use it with value. Change your code to this:
posts.value = response.data;
It should be working fine. For more detail you should check here:
https://vuejs.org/api/reactivity-core.html#ref

Vuejs & Auth0 : I need to reload page to be Authenticated

I'm a beginner in Vue, and I implemented Auth0 to my Web App using Vue3.
My issue: after logging in, my API call to retrieve data get an unauthorized error 403. If I reload the page, everything is working fine.
What should I do to avoid reloading the page to get authenticated directly?
Here are my scripts:
Main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './index.css'
import dayjs from 'dayjs'
import Datepicker from 'vue3-date-time-picker'
import 'vue3-date-time-picker/dist/main.css'
import { setupAuth } from './auth/index.js'
import authConfig from './auth/config.js'
function callbackRedirect(appState) {
router.push(appState && appState.targetUrl ? appState.targetUrl : '/' );
}
setupAuth(authConfig, callbackRedirect).then((auth) => {
let app = createApp(App).use(router);
app.config.globalProperties.$dayjs = dayjs;
app.component('Datepicker', Datepicker);
app.use(auth).mount('#app');
})
My App.vue script:
<template>
<div v-if="isAuthenticated">
<NavBar />
<router-view/>
</div>
</template>
<script>
import NavBar from './components/NavBar.vue'
export default {
components: { NavBar },
data(){
return {
isAuthenticated: false,
}
},
async mounted(){
await this.getAccessToken()
},
methods: {
async getAccessToken(){
try {
const accessToken = await this.$auth.getTokenSilently()
localStorage.setItem('accessToken', accessToken)
this.isAuthenticated = true
} catch (error) {
console.log('Error occured while trying to retrieve Access Token...', error)
}
},
},
}
</script>
and my Home.vue loading the data:
<template>
<div class="home">
<div class="py-10">
<header>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<h1 class="text-3xl font-bold leading-tight text-gray-900">Monitoring Dashboard</h1>
</div>
</header>
<main>
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<h3 class="m-5 text-lg leading-6 font-medium text-gray-900">Main KPIs</h3>
<div class="md:grid md:grid-cols-3 md:gap-6">
<div v-for="(item, index) in stats" :key="index" class="md:col-span-1">
<div class="bg-white p-5 border-gray-50 rounded-lg shadow-lg mb-5">
<span class="text-sm font-medium text-gray-500 truncate">{{ item.name }}</span>
<p class="mt-1 text-3xl font-bold text-gray-900">{{ parseFloat(item.stat.toFixed(2)) }}</p>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
</template>
<script>
import _ from 'lodash'
import ProductsService from '../services/products.service'
export default {
name: 'Home',
data(){
return{
user: '',
products: '',
stats: '',
}
},
async mounted(){
await this.readProducts()
await this.buildStats()
},
methods: {
async readProducts(){
let temp = null
try {
temp = await ProductsService.readProducts()
this.products = temp.data
} catch (error) {
console.log('Error: cannot retrieve all products...')
}
},
async buildStats(){
//Nb products
const nbProducts = this.products.length
//Nb offers & Uniq NbRetailers
let nbOffers = 0
let retailers = []
for(let product of this.products){
for(let offer of product.offers){
retailers.push(offer.retailer)
nbOffers += 1
}
}
const nbRetailers = _.uniq(retailers).length
this.stats = [
{ name: 'Number of Retailers', stat: nbRetailers },
{ name: 'Number of Products', stat: nbProducts },
{ name: 'Number of Offers', stat: nbOffers },
]
},
},
watch: {
products: function(){
this.buildStats()
}
}
}
</script>
My ./auth/index.js file:
import createAuth0Client from '#auth0/auth0-spa-js'
import { computed, reactive, watchEffect } from 'vue'
let client
const state = reactive({
loading: true,
isAuthenticated: false,
user: {},
popupOpen: false,
error: null,
})
async function loginWithPopup() {
state.popupOpen = true
try {
await client.loginWithPopup(0)
} catch (e) {
console.error(e)
} finally {
state.popupOpen = false
}
state.user = await client.getUser()
state.isAuthenticated = true
}
async function handleRedirectCallback() {
state.loading = true
try {
await client.handleRedirectCallback()
state.user = await client.getUser()
state.isAuthenticated = true
} catch (e) {
state.error = e
} finally {
state.loading = false
}
}
function loginWithRedirect(o) {
return client.loginWithRedirect(o)
}
function getIdTokenClaims(o) {
return client.getIdTokenClaims(o)
}
function getTokenSilently(o) {
return client.getTokenSilently(o)
}
function getTokenWithPopup(o) {
return client.getTokenWithPopup(o)
}
function logout(o) {
return client.logout(o)
}
export const authPlugin = {
isAuthenticated: computed(() => state.isAuthenticated),
loading: computed(() => state.loading),
user: computed(() => state.user),
getIdTokenClaims,
getTokenSilently,
getTokenWithPopup,
handleRedirectCallback,
loginWithRedirect,
loginWithPopup,
logout,
}
export const routeGuard = (to, from, next) => {
const { isAuthenticated, loading, loginWithRedirect } = authPlugin
const verify = () => {
// If the user is authenticated, continue with the route
if (isAuthenticated.value) {
return next()
}
// Otherwise, log in
loginWithRedirect({ appState: { targetUrl: to.fullPath } })
}
// If loading has already finished, check our auth state using `fn()`
if (!loading.value) {
return verify()
}
// Watch for the loading property to change before we check isAuthenticated
watchEffect(() => {
if (loading.value === false) {
return verify()
}
})
}
export const setupAuth = async (options, callbackRedirect) => {
client = await createAuth0Client({
...options,
})
try {
// If the user is returning to the app after authentication
if (
window.location.search.includes('code=') &&
window.location.search.includes('state=')
) {
// handle the redirect and retrieve tokens
const { appState } = await client.handleRedirectCallback()
// Notify subscribers that the redirect callback has happened, passing the appState
// (useful for retrieving any pre-authentication state)
callbackRedirect(appState)
}
} catch (e) {
state.error = e
} finally {
// Initialize our internal authentication state
state.isAuthenticated = await client.isAuthenticated()
state.user = await client.getUser()
state.loading = false
}
return {
install: (app) => {
app.config.globalProperties.$auth = authPlugin
},
}
}

nuxtServerInit data not show in page

I try to use nuxtServerInit method.
index.js
import productsService from "../services/productsService";
export const state = () => ({
hotDeals: [],
specialities: []
})
export const mutations = {
SET_SPECIALITIES(state, payload) {
state.specialities = payload;
}
}
export const actions = {
async nuxtServerInit({ dispatch}, ctx) {
try {
await dispatch('fetchSpecialities');
}catch (e) {
console.log(e);
}
},
fetchSpecialities({ commit }) {
productsService.getSpecialities()
.then(response => {
commit('SET_SPECIALITIES', response.data);
});
}
}
component usage
<template>
<v-layout
justify-center
align-center
>
<div>
<v-row >
<span v-for="item in specialities">{{item.productCode}}</span>
</v-row>
</div>
</v-layout>
</template>
<script>
import { mapState } from 'vuex';
export default {
computed: {
...mapState(["specialities"])
}
}
</script>
But it show nonthing on page. If I try to use console.log(state.specialities) in mutation after change state I can see data in web storm console. But in component data is not showing.
i think using watchers will solve your problem
watch: {
specialities(newValue, oldValue) {
console.log(`Updating from ${oldValue} to ${newValue}`);
},
},

Vue.js return data from axios

<template>
<div class="comment">
<div v-for="(comment, index) in comments" :key="index">
{{ getUser(comment.student_idx) }}
</div>
</div>
</template>
<script>
import axios from 'axios'
import server from '#/models/server'
export default {
data() {
return {
url: server,
comments: {}
}
},
props: ['idx'],
created() {
axios.get(`${this.url}/bamboo/reply?post=${this.idx}`)
.then(response => {
if (response.data.status === 200) {
this.comments = response.data.data.replies
}
})
},
methods: {
getUser (idx) {
axios.get(`${this.url}/member/student/${idx}`)
.then(response => {
if (response.data.status === 200) {
return response.data.data.member.name
}
})
}
}
}
</script>
I would like to load the comments at created and print them out using v-for.
In v-for, I would like to load the member.name from each comment
But {{ getUser(comment.student_idx) }} is undefined.
I don't know how to return data from axios
Help me please!!
Your method should not be async for stable run code. My recomendation is next code:
<template>
<div class="comment">
<div v-for="(comment, index) in comments" :key="index">
{{ comments['user'] }}
</div>
</div>
</template>
<script>
import axios from 'axios'
import server from '#/models/server'
export default {
data() {
return {
url: server,
comments: []
}
},
props: ['idx'],
created() {
axios.get(`${this.url}/bamboo/reply?post=${this.idx}`)
.then(response => {
if (response.data.status === 200) {
this.comments = response.data.data.replies;
if(this.comments)
for(let comment of this.comments){
this.getUser(comment, comment.student_idx);
}
}
})
},
methods: {
getUser (comment, idx) {
axios.get(`${this.url}/member/student/${idx}`)
.then(response => {
if (response.data.status === 200) {
this.$set(comment, 'user', response.data.data.member.name);
}
})
}
}
}
</script>

Call $emit after dispatch action in Vuejs

I have a parent component:
<template>
<div class="w-full">
<div class="card-body">
<city-edit-form :form="form" :resource="resource" #save_resource="func">
</city-edit-form>
</div>
</div>
</template>
<script>
export default {
methods: {
func() {
console.log("test");
}
}
};
</script>
And child component:
<template>
<div>
<form action="#" method="POST" #submit.prevent="submit" v-else>
<button type="submit" class="btn-green">Save</button>
</form>
</div>
</template>
<script>
import { UPDATE_RESOURCE } from "../../../Stores/action-types";
export default {
props: {
form: { required: true },
resource: { required: true }
},
methods: {
submit() {
this.$store
.dispatch(`city/${UPDATE_RESOURCE}`, this.form)
.then(() => this.$emit("save_resource"));
}
}
};
</script>
And action is:
[UPDATE_RESOURCE]({ commit, state }, form) {
commit(SET_LOADING, true);
return ResourceService.update(state.resource.id, form)
.then(({ data }) => {
commit(SET_RESOURCE, data);
})
.catch(errors => {
commit(SET_ERRORS, errors.response.data);
})
.finally(() => commit(SET_LOADING, false));
});
},
When I submit form, action has been dispatched, but nothing emitted.
Nothing logged in console. Where I make mistake?
update
When I check Vue toolbar's Event tab, I see this:
I think event has been emmitted, but console.log logs nothing in console! So wired!
Use return keyword while resolve or reject is triggered
[UPDATE_RESOURCE]({ commit, state }, form) {
commit(SET_LOADING, true);
return new Promise((resolve, reject) => {
ResourceService.update(state.resource.id, form)
.then(({ data }) => {
commit(SET_RESOURCE, data);
return resolve();
})
.catch(errors => {
commit(SET_ERRORS, errors.response.data);
return reject();
})
.finally(() => commit(SET_LOADING, false));
});
},
instead of emitting events (nothing wrong with that) you could use mapGetters
<template>
<div class="w-full">
<div class="card-body">
<city-edit-form :form="form" :resource="myResource">
</city-edit-form>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
myResource: 'Stores/action-types/SET_RESOURCE', <---- needs to be modified
}),
}
};
</script>
this is assuming you have made any getters