N
Nuxtwhatstaz

Where to fetch initial user data

What is the best practice to load initial user data? Currently I do it in the default.vue layout in an onMounted hook, but that doesn't seem like the right way as sometimes it doesn't work. Here is the code:
const userStore = useUserStore()

const { user } = storeToRefs(userStore)

const accountStore = useAccountsStore()
const categoryStore = useCategoryStore()
const payeeStore = usePayeeStore()
const transactionStore = useTransactionStore()

onMounted(() => {
if (!accountStore.isInitialized) {
accountStore.getAccounts()
accountStore.initialized()
}
if (!categoryStore.isInitialized) {
categoryStore.getCategories()
categoryStore.initialized()
}
if (!transactionStore.isInitialized) {
transactionStore.getTransactions()
transactionStore.initialized()
}
if (!payeeStore.isInitialized) {
payeeStore.getPayees()
payeeStore.initialized()
}
})
const userStore = useUserStore()

const { user } = storeToRefs(userStore)

const accountStore = useAccountsStore()
const categoryStore = useCategoryStore()
const payeeStore = usePayeeStore()
const transactionStore = useTransactionStore()

onMounted(() => {
if (!accountStore.isInitialized) {
accountStore.getAccounts()
accountStore.initialized()
}
if (!categoryStore.isInitialized) {
categoryStore.getCategories()
categoryStore.initialized()
}
if (!transactionStore.isInitialized) {
transactionStore.getTransactions()
transactionStore.initialized()
}
if (!payeeStore.isInitialized) {
payeeStore.getPayees()
payeeStore.initialized()
}
})
Any help would be greatly appreciated!
P
pyplacca15d ago
it depends on how you want your app to function. if you want the user data to be fetched before the app loads for instance, you could use a middleware
W
whatstaz15d ago
Ah okay, does that still trigger when a user is trying to log in?
P
pyplacca15d ago
It depends on how you design it, but it’s achievable
W
whatstaz15d ago
Okay thanks for the help!
P
pyplacca15d ago
Welcome
T
Tirius14d ago
Plugin also could be an option
// plugins/init.client.js
import { useGeneralStore } from '~/stores/generalStore';
import { useUserStore } from '~/stores/userStore';

export default defineNuxtPlugin(async () => {
const generalStore = useGeneralStore();
const userStore = useUserStore();

await Promise.all([
generalStore.init(),
userStore.init()
]);
});
// plugins/init.client.js
import { useGeneralStore } from '~/stores/generalStore';
import { useUserStore } from '~/stores/userStore';

export default defineNuxtPlugin(async () => {
const generalStore = useGeneralStore();
const userStore = useUserStore();

await Promise.all([
generalStore.init(),
userStore.init()
]);
});
HJ
Hendrik Jan14d ago
You could try it in "app.vue" (you probably have to create that file, see the docs). Simplified example of my code (I'm using Nuxt useState as you can see):
// app.vue
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>

<script setup lang="ts">
const userData = useState('user');

const data = await useFetch(...);
userData.value = data.value.user;
</script>
// app.vue
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>

<script setup lang="ts">
const userData = useState('user');

const data = await useFetch(...);
userData.value = data.value.user;
</script>
W
whatstaz14d ago
That is kinda what I'm doing right now, I found my problem, I was calling my loadUserData in a default.vue layout (which loaded on the login page), after the login, it didn't trigger any more unless I refreshed. I tried the middleware but then it was triggering twice and I could not get rid of the hydration mismatch.
P
pyplacca14d ago
here's what I normally use to prevent the double call in the middleware
export default defineNuxtRouteMiddleware(() => {
// Single execution client-only actions
if (process.server || (process.client && !nuxtApp.isHydrating)) return
// any code below this line will be run once on the client side
})
export default defineNuxtRouteMiddleware(() => {
// Single execution client-only actions
if (process.server || (process.client && !nuxtApp.isHydrating)) return
// any code below this line will be run once on the client side
})
Want results from more Discord servers?
Add your server
More Posts
Protecting static folder on server sideI have a folder with statically built HTML, CSS and JS assets (think static dashboard) that I wouldnuxt v2 upgrade to v3 errorHello guys, we have project which is build with nuxt v2, but now i updated it to v3, and im getting [RESOLVED] Nuxt3 and netlify hosting env variablesHey! First of all "Nuxt3 is epic!". But I need some help with Nuxt 3 Netlify environment variables. Nuxt 3 dayjs moduleI try to use dayjs module in my pnpm monorepo i follow all the documentation but when i use dayjs iHow to set meta theme-color in nuxt.config``` app: { head: { ... meta: [{ theme_color: '#ffffff', }], }, },``` Testing Nuxt 3 API EndpointsHi, I would like to test my Nuxt 3 server api endpoints. I know I could test it for example in posNitro: How do I pass data in a middleware to route handlers?In Express, you can do this attaching data to the `response.locals` object. How do I do this in NitrMake `useRoute()` update in layoutHi! Im trying to use useRoute() in a layout, to update my navigations links based on the ´route.paraHow do you set a PostCSS parser in the `nuxt.config.ts`?I'm trying to do that but it seems the "parser" option isn't allowed on the object.Auto-import only Nuxt and Vue features but no custom or third party codeHey! I wonder: is it possible to disable auto imports for components, composables, and utils while kuseAsyncData weird behaviorHi guys, I'm experiencing a strange behavior. I'm using async data to call an API. But there is a coProblem with sending POST/GET Request at the same timeNow I'm looking to load the last projects of a user from the database by sending his name and receivNuxt Content behind CloudflareWhen I use Nuxt Content behind Cloudflare, I have the issue that some pages (but not all) cannot be Odd situation with Nuxt hosting and site accessibilityHey everyone. First post on this Discord. We have a Nuxt app (an intranet, small company app) that wUButton showing over sticky headerI have a table and one of the columns is filled with Nuxt UI buttons. I have a sticky header for thiPinia as a layerHi, I’m learning pinia, and I like it so much I thought it should be a layer. Does it makes sense? IFetchError typeI've seen `import type { FetchError } from 'ofetch'`, what what's the correct module when handling `How to import functions in a .vue component from a .js file?import { myfunctions} from "/js/stats.js" doesnt work for me: Error 500 __vite_ssr_import_7__.defauskeleton does not work on dynamic routesguys, can anyone help me? the skeleton is appearing on the main page but on the page where the produhow to generate static HTML pages just for some of the routesI'm trying to generate 4 static HTML pages from a huge list of routes that the app has But I only se