Init pinia state - vue.js

We use pinia to manage app state. As it's mentioned in title, I'm looking for NuxtServerInit hook analogue for pinia.
A little context: User lands on First page of form; Form calls (f.e.) state.getCountries() to fetch the list of items for one of the select inputs; User selects a country and navigates to Second page, which has to have access to countries list as well; It's ok, when User goes to Second page from the First page; But countries list is empty (obvious) if User refreshes the Second page;
Atm I do like if (state.countries.length === 0) state.getCountries()
But, I believe, it's not a good way
Page 1
<template>
<app-select :items="send.countries" />
</template>
<script>
import { defineComponent } from '#nuxtjs/composition-api'
import { useSend } from '~/store/send'
export default defineComponent({
setup() {
const send = useSend()
send.getCountries()
return { send }
}
}
</script>
Page 2
<template>
<app-select :items="send.countries" />
</template>
<script>
import { defineComponent } from '#nuxtjs/composition-api'
import { useSend } from '~/store/send'
export default defineComponent({
setup() {
const send = useSend()
// if User refreshed Second page, countries is empty list
if (send.countries.length === 0) {
send.getCountries()
}
return { send }
}
}
</script>
store/send.ts
import { defineStore } from 'pinia'
export const useSend = defineStore({
state: () => {
return {
countries: []
}
},
actions: {
getCountries() {
const res = this.$nuxt.$api.countries.get()
this.countries = res.data
}
}
})

Related

How to use $store.commit in Nuxt with #vue/composition-api

<template>
<div>
<h1>Vuex Typescript Test</h1>
<button #click="handleLogin">click</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from '#vue/composition-api'
export default defineComponent({
setup() {
return {
handleLogin() {
// something....
},
}
},
})
</script>
#vue/composition-api do not apply useStore
I want to use store in setup function.
You should be able to access the useStore composable in the setup function according to the documentation of Vuex.
Your script section will look like this:
import { defineComponent } from '#vue/composition-api';
import { useStore } from 'vuex';
export default defineComponent({
setup() {
return {
const store = useStore();
return {
handleLogin {
store.dispatch('auth/login');
},
};
}
},
});
The proper way to structure the content of setup would be to move the handleLogin as a separate const and expose the constant in the return, in order to keep the return section more readable like this:
setup() {
const store = useStore();
const handleLogin = () => {
store.dispatch('auth/login');
};
return {
handleLogin,
}
}

Nuxt js / Vuex Cannot get state variables on components which is set by nuxtServerInit

I am trying to get the state variable on components which is set by the nuxtServerInit Axios by get method.
store/state.js
export default () => ({
siteData: null
})
store/mutations.js
import initialState from './state'
const mutations = {
SET_SITE_DATA (state, value) {
state.siteData = {
site_title: value.site_title,
logo: value.logo
}
}
}
export default {
...mutations
}
store/getters.js
const getters = {
siteDetails: state => state.siteData
}
export default {
...getters
}
store/actions.js
const actions = {
async nuxtServerInit ({ commit, dispatch }, ctx) {
try {
const host = ctx.req.headers.host
const res = await this.$axios.post('/vendors/oauth/domain/configuration', { domain: host })
commit('SET_SITE_DATA', res.data.data.site_data)
} catch (err) {
console.error(err)
}
},
export default {
...actions
}
}
store/index.js
import Vuex from 'vuex'
import mutations from './mutations'
import getters from './getters'
import actions from './actions'
import state from './state'
const store = () => {
return new Vuex.Store({
state,
getters,
mutations,
actions
})
}
export default store
Here I set SET_SITE_DATA mutation which set siteData state.
components/Header.vue
<template>
<section class="header sticky-top">
<client-only>
{{ siteDetails }}
{{ $store.getters }}
{ logo }}
</client-only>
</section>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['siteDetails']),
logo () {
console.log(this.$store.state.siteData)
return this.$store.state.siteData
}
}
}
</script>
Console
I don't know what is happening here. You can see I have consoled the values. So when I reload the page I can get the values but after few seconds all values reset to the null. I want to set those values globally so can access them all over the site. I don't want to call API every time a page changes so I used nuxtServerInit so can set values globally when the page reloads once and can access them.

How to get set in composition api for step form?

I am trying to create a multi step form with composition api.
In vue 2 I used to do it this way
email: {
get() {
return this.$store.state.email
},
set(value) {
this.$store.commit("setEmail", value)
}
},
Now I have my own store, I made this computed property to pass to my component stEmail: computed(() => state.email). How can I actually use this in get set?
I am trying do something like this but completely doesn't work.
let setMail = computed(({
get() {
return stEmail;
},
set(val) {
stEmail.value = val;
}
}))
const state = reactive({
email: "",
})
export function useGlobal() {
return {
...toRefs(state),
number,
}
}
Or is there better way now to make multi step forms?
You can do the same with the Composition API. Import useStore from the vuex package and computed from vue:
import { computed } from 'vue';
import { useStore } from 'vuex';
And then use it in your setup() function like this:
setup: () => {
const store = useStore();
const email = computed({
get() {
return store.state.email;
},
set(value) {
store.commit("setEmail", value);
}
});
return { email };
}
If you want to avoid using vuex, you can just define variables with ref() and export them in a regular JavaScript file. This would make your state reusable in multiple files.
state.js
export const email = ref('initial#value');
Form1.vue/Form2.vue
<template>
<input v-model="email" />
</template>
<script>
import { email } from './state';
export default {
setup() {
return { email };
}
};
</script>
As Gregor pointed out, the accepted answer included an anonymous function that doesn't seem to work, but it will work if you just get rid of that part. Here's an example using <script setup> SFC
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const email = computed({
get() {
return store.state.email
},
set(value) {
store.commit("setEmail", value)
}
})
</script>
<template>
<input type="email" v-model="email" />
</template>

How can I access HEAD data in component with nuxt?

In a page, I set head title like this:
...
<script>
export default {
head() {
return {
title: this.post.name
}
}
}
</script>
How can I get this data in another component?
I tried with this.$metaInfo but my component where I need to get data is in the layout outside <nuxt />...
Also, If the current route is in a child page with populated head, it's override the parent title. So, how do I do?
this.$metaInfo will be accessible just in the page component. If you want to have the title of the current page anywhere, I think the best way is using the store to save the current title then retrieve this information easily in any component.
In store/index.js
export const state = {
title: 'Default Title'
}
export const mutations = {
SET_TITLE (state, title) {
state.title= title
}
}
Then use this on the pages components
<template>
<div></div>
</template>
<script>
export default {
head () {
return {
title: this.title
}
},
mounted () {
this.$store.commit('SET_TITLE', this.$metaInfo.title)
}
}
</script>
Now, you can access the current title in any component you are retrieving it from the store state.
<template>
<div></div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
title: state => state.title
})
}
}
</script>
you can walk up the component tree until you reach the page-component
metaInfoTitle() {
let curr = this
let title = null
do {
title = curr?.$metaInfo?.title
curr = curr.$parent
} while (!title && curr)
return title
},

currentUser not getting set with Vuex

I added some code to my vue project so I can save the state of a user - which is whether he is logged in or not. If the state is not null, I want to display the navbar and footer. I added all the vuex import statements. I am using an axios call to the db which returns a json response. response.data comes back as true/false. If true, I redirect the user to the main page. Then I create a user object called currentUser, but I'm not sure what to base it on, so it is getting set to null. I need to use the state in a few places throughout my app, but it is not getting set. Please someone help. Thanks in advance. (code is below)
User.js:
import JwtDecode from 'jwt-decode'
export default class User {
static from (token) {
try {
let obj = JwtDecode(token)
return new User(obj)
} catch (_) {
return null
}
}
constructor ({username}) {
this.username = username
}
}
App.vue:
<template>
<div id="app">
<template v-if="currentUser">
<Navbar></Navbar>
</template>
<div class="container-fluid">
<router-view></router-view>
<template v-if="currentUser">
<Foot></Foot>
</template>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import Navbar from '#/components/Navbar'
import Foot from '#/components/Foot'
export default {
name: 'App',
components: {
Navbar,
Foot
},
computed: {
...mapGetters({ currentUser: 'currentUser' })
},
mutation_types.js:
export const LOGIN = 'LOGIN'
export const LOGOUT = 'LOGOUT'
auth.js:
/* global localStorage */
import User from '#/models/User'
import * as MutationTypes from './mutation_types'
const state = {
user: User.from(localStorage.token)
}
const mutations = {
[MutationTypes.LOGIN] (state) {
state.user = User.from(localStorage.token)
},
[MutationTypes.LOGOUT] (state) {
state.user = null
}
}
const getters = {
currentUser (state) {
return state.user
}
}
const actions = {
login ({ commit }) {
commit(MutationTypes.LOGIN)
},
logout ({ commit }) {
commit(MutationTypes.LOGOUT)
}
}
export default {
state,
mutations,
getters,
actions
}
The user store should only set the default state. AFter making request to validate user. You should use actions and mutations to set the user state. Call the action via store.dispatch("user/login", user) where you return new User(obj).
let obj = JwtDecode(token)
const user = new User(obj)
store.dispatch("user/login", user)
const actions = {
login ({ commit }, userObject) {
commit(MutationTypes.LOGIN, userObject)
},
logout ({ commit }) {
commit(MutationTypes.LOGOUT)
}
}
const mutations = {
[MutationTypes.LOGIN] (state, user) {
state.user = user;
},
[MutationTypes.LOGOUT] (state) {
state.user = null
}
}
On a other note, you have dumb getters. Meaning they just return the state. You can rather call the user object directly out of state. Use getters when you want to modify the return value before returning it.
I took a little look and it seems you use '=' instead of Vue.set() to set your state variable.
Refer to the answer : vuex - is it possible to directly change state, even if not recommended?