Phillip
Phillip
NNuxt
Created by Phillip on 11/4/2024 in #❓・help
`getCachedData`: data is always undefined
In my app.vue I'm getting user data from supabase. I want to cache the values so I don't have to do it on every cache load. I followed this YouTube tutorial by @manniL https://www.youtube.com/watch?v=aQPR0xn-MMk&t=336s&ab_channel=AlexanderLichter But for some reason this line of code always returns undefined, causing my code to refetch and not using any cache. Why is that?:
const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
console.log('data', data) // always returns undefined
const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
console.log('data', data) // always returns undefined
Here is my full code:
constdata: userDataAsync } = await useAsyncData('userStoreData', async () => {
if (user.value && !isAdmin) {
const userData = await userStore.fetchInitialData()
console.log('userdata in useasyncdata', userData)
return userData
}
},
{
watch: [user],
getCachedData(key) {
console.log('key', key)
const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
console.log('data', data)

// refetch
if (!data) return

const expirationDate = new Date(data.fetchedAt)
expirationDate.setTime(expirationDate.getTime() + 24 * 60 * 60 * 1000);
const isExpired = expirationDate.getTime() < Date.now()

// refetch
if (isExpired) return

return data
}
})

if (userDataAsync.value) {
userStore.setInitialData(userDataAsync.value)
}
constdata: userDataAsync } = await useAsyncData('userStoreData', async () => {
if (user.value && !isAdmin) {
const userData = await userStore.fetchInitialData()
console.log('userdata in useasyncdata', userData)
return userData
}
},
{
watch: [user],
getCachedData(key) {
console.log('key', key)
const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
console.log('data', data)

// refetch
if (!data) return

const expirationDate = new Date(data.fetchedAt)
expirationDate.setTime(expirationDate.getTime() + 24 * 60 * 60 * 1000);
const isExpired = expirationDate.getTime() < Date.now()

// refetch
if (isExpired) return

return data
}
})

if (userDataAsync.value) {
userStore.setInitialData(userDataAsync.value)
}
Using Nuxt 3.12.2 Any advice is highly appreciated 🙏
7 replies
NNuxt
Created by Phillip on 10/10/2024 in #❓・help
Do Cronjobs / Webhooks have an H3 Event?
Hi, I have cronjobs and webhooks who perform regular tasks. As far as I understand a H3 event is passed by a user who makes an API call for example. Cronjobs do not contain a H3 Event right? Because some utilities require to pass an event. For example, the i18n module needs an event on the server side. await useTranslation(event) If I would do something like:
export default defineCronHandler('everyFiveMinutes', async () => {
const t = await useTranslation(useEvent())
}
export default defineCronHandler('everyFiveMinutes', async () => {
const t = await useTranslation(useEvent())
}
This would not work?
1 replies
NNuxt
Created by Phillip on 7/20/2024 in #❓・help
Nested routes: Showing parent page only in campaigns/choose-type.vue, but not other routes?
This question is a bit tricky but I try my best to explain it properly. I have a file structure like this: campaigns.vue -- choose-type.vue -- create.vue -- edit -- detail -- [campaignId].vue pages/campaigns.vue: shows overview of campaigns pages/campaigns/choose-type.vue: shows a modal. I want to have the pages/campaigns.vue in the background. I have already accomplished that with the file structure and adding <NuxtPage /> to pages/campaigns.vue However, other routes such as pages/campaigns/create.vue also show the pages/campaigns.vue (campaign table) which I don't want. I have tried something like <NuxtPage v-if="route.name === 'portal-campaigns-choose-type" /> but that didn't work. Is there a way to accomplish that? I have already read the docs regarding nested pages. Help is very appreciated
1 replies
NNuxt
Created by Phillip on 7/20/2024 in #❓・help
"Cannot find module or its corresponding type declarations.ts(2307)"
Hey there, I'm having trouble importing my types and constants with the @ directive. It used to work like this:
import { ICampaign, ICampaignApiData, IFacebookUpdateResponse, TCampaignStatus } from '@/types/facebook';
import { CREATE_NEW_CAMPAIGN, CAMPAIGN_EDIT_DETAIL, CAMPAIGNS_OVERVIEW_CHOOSE_TYPE } from '@/constants/routes'
import { ICampaign, ICampaignApiData, IFacebookUpdateResponse, TCampaignStatus } from '@/types/facebook';
import { CREATE_NEW_CAMPAIGN, CAMPAIGN_EDIT_DETAIL, CAMPAIGNS_OVERVIEW_CHOOSE_TYPE } from '@/constants/routes'
But now I'm getting "Cannot find module '@/constants/routes' or its corresponding type declarations.ts(2307)" When I try to access the files without @ it works. Why is that?
2 replies
NNuxt
Created by Phillip on 7/11/2024 in #❓・help
How to use DefinitelyTyped types in a Nuxt 3 project?
I've been trying to use DefinitelyTyped types in my project multiple times but just cannot get it working. Is there an additional step that I need to do? 1. installed types for Google Maps with npm i @types/google.maps (https://www.npmjs.com/package/@types/google.maps) 2. in my script setup I try to import an interface like this:
<script setup lang="ts">
import { GeocoderResult } from '@types/google.maps'
<script setup lang="ts">
import { GeocoderResult } from '@types/google.maps'
A index.d.ts is present in @types/google.maps but I'm getting 'GeocoderResult' is declared but its value is never read.ts(6133) Cannot import type declaration files. Consider importing 'google.maps' instead of '@types/google.maps'.ts(6137) Do I need to add something else to my tsconfig? Edit: Okay I just read it's not possible to import index.d.ts file as it seems... but how am I supposed to use the interface in @types/google.maps?
3 replies
NNuxt
Created by Phillip on 6/30/2024 in #❓・help
appMiddleware for API routes?
When an API under /api/admin is being called I want to run my middleware under /server/middleware/admin.ts I thought I could add a route rule to the nuxt.config.ts like this:
routeRules: {
'/api/admin/**': { appMiddleware: 'admin' }
},
routeRules: {
'/api/admin/**': { appMiddleware: 'admin' }
},
But still, the middleware runs on every request which is also mentioned in the docs (https://nuxt.com/docs/guide/directory-structure/server#server-middleware) But I was wondering if something like this '/api/admin/**': { appMiddleware: 'admin' } is possible? Otherwise I would need to do something like if (requestUrl.includes('/api/admin')) right?
1 replies
NNuxt
Created by Phillip on 6/28/2024 in #❓・help
appMiddleware in routeRules not working?
I want to run a middleware when my API in /server/api/admin/text-snippet.post.ts is being called but it doesn't run the middleware at all. Nuxt 3.12.2 nuxt.config.ts
routeRules: {
"/portal": { redirect: START_PAGE_AFTER_LOGIN },
'/portal/**': { ssr: false },
'/server/api/admin/**': { appMiddleware: 'mytest' }
},
routeRules: {
"/portal": { redirect: START_PAGE_AFTER_LOGIN },
'/portal/**': { ssr: false },
'/server/api/admin/**': { appMiddleware: 'mytest' }
},
middleware/mytest.ts
export default defineNuxtRouteMiddleware(async (to, _from) => {
console.log('getting in middleware') // <-- the issue: this is never being called
return false
})
export default defineNuxtRouteMiddleware(async (to, _from) => {
console.log('getting in middleware') // <-- the issue: this is never being called
return false
})
server/api/admin/text-snippet.post.ts
export default defineEventHandler(async (event) => {
console.log('getting in API') // <-- getting called
return { success: true }
})
export default defineEventHandler(async (event) => {
console.log('getting in API') // <-- getting called
return { success: true }
})
Then, I access the API via Postman. Method: Post. URL: http://localhost:3000/api/admin/text-snippet The response is { success: true } What am I missing or is this a bug?
7 replies
NNuxt
Created by Phillip on 6/16/2024 in #❓・help
Private server routes
Hello guys, how can i flag my nuxt 3 api routes as private meaning they can only be accessed from the server itself and is not viewable by the user? Since every API file I put inside /server/api, but also /server/, will be accessible by other users. How can I prevent this?
6 replies
NNuxt
Created by Phillip on 3/27/2024 in #❓・help
Is there a way to prefetch the next page which has content that is being injected by javascript?
I have a page /welcome/payment-method where I load a Stripe UI payment element. Stripe has a function paymentElement.mount('#payment-element'), so basically, it looks for a DOM element with the id #payment-element. However, injecting the Stripe script and mounting the element takes time. I would like to show the form immediately. Is there way I can load the stripe script + mount the div#payment-element before the user visits the page /welcome/payment-method? Can I prepare this while the user is on page /welcome/intro or something? I hope my question is clear. I'm happy to explain further. Thank you!
2 replies
NNuxt
Created by Phillip on 3/27/2024 in #❓・help
How to access the event in a server/utils function?
I've created a server utility function in /server/utils/get-facebook-account.ts which looks like this
import { serverSupabaseClient } from '#supabase/server'

export const getFacebookAccount = async () => {
// const event = // how to get event
const supabase = await serverSupabaseClient<Database>(event)

const account = supabase.from()... // do stuff to get account;

return account;
}
import { serverSupabaseClient } from '#supabase/server'

export const getFacebookAccount = async () => {
// const event = // how to get event
const supabase = await serverSupabaseClient<Database>(event)

const account = supabase.from()... // do stuff to get account;

return account;
}
I'm using Supabase so for the serverSupabaseClient I need the event. Now I'm wondering, do I always need to pass the event to my utility function like this? /server/api/campaign.post.ts
export default defineEventHandler(async (event) => {
await getFacebookAccount(event)
})
export default defineEventHandler(async (event) => {
await getFacebookAccount(event)
})
Because I've read there is a useRequestEvent composable but it's only available in the Nuxt context. Is there something similar for /server functions? Thanks!
3 replies
NNuxt
Created by Phillip on 3/2/2024 in #❓・help
await useAsyncData in setup doesn't block navigation
I want to wait until navigating to the next page until the store data has been fetched and set. I'm using Nuxt 3 + Supabase + Pinia My approach in provider.vue (where user gets redirected after signing in/up to set cookies etc.)
// redirect once user has been set
const user = useSupabaseUser()
watch(user, async () => {
if (user.value) {
await useSteps().handleNavigateToNextStep()
}
}, { immediate: true })
// redirect once user has been set
const user = useSupabaseUser()
watch(user, async () => {
if (user.value) {
await useSteps().handleNavigateToNextStep()
}
}, { immediate: true })
app.vue: fetch store data. I'm hoping to block navigation by using await useAsyncData
const user = useSupabaseUser()
await useAsyncData('userStoreData', async () => {
if (user.value) {
await useUserStore().fetchInitialData()
}
}, { watch: [user] })
const user = useSupabaseUser()
await useAsyncData('userStoreData', async () => {
if (user.value) {
await useUserStore().fetchInitialData()
}
}, { watch: [user] })
my store (reduced data for demonstration purpose)
export const useUserStore = defineStore({
id: 'UserStore',
state: () => ({
company: null as Tables<'company'> | null,
}),
actions: {
async fetchInitialData() {
const [companyData] = await Promise.all([
useCompany().getCompany(),
])
this.company = companyData;
},
}
})
export const useUserStore = defineStore({
id: 'UserStore',
state: () => ({
company: null as Tables<'company'> | null,
}),
actions: {
async fetchInitialData() {
const [companyData] = await Promise.all([
useCompany().getCompany(),
])
this.company = companyData;
},
}
})
... however, after the provider.vue redirects me, this value is undefined in one of my composables: const { company } = storeToRefs(useUserStore()) How can I make the application wait until the store has been set?
1 replies
NNuxt
Created by Phillip on 6/11/2023 in #❓・help
How can I use tailwind @apply within a style tag?
Like this:
<style lang="scss" scoped>
a.nuxt-link-active {
@apply .bg-indigo-700 .text-white;
}
</style>
<style lang="scss" scoped>
a.nuxt-link-active {
@apply .bg-indigo-700 .text-white;
}
</style>
I'm using @Nuxtjs/tailwindcss with Nuxt 3
3 replies
NNuxt
Created by Phillip on 2/28/2023 in #❓・help
How to enforce redirecting to HTTPS?
No description
4 replies