Skip to content

Instantly share code, notes, and snippets.

@davidparys
Created January 27, 2025 23:09
Show Gist options
  • Save davidparys/afea9cbf8f1eb269ec01e97fd0e756d7 to your computer and use it in GitHub Desktop.
Save davidparys/afea9cbf8f1eb269ec01e97fd0e756d7 to your computer and use it in GitHub Desktop.
<script setup lang="ts">
const {
coursesEn,
coursesDe,
isLoading,
learndashEn
} = useLearndashCache()
// Example of using SWR pattern for a specific course
const useCourse = async (id: string) => {
const { data, refresh } = await learndashEn.getWordpressData({
ep: 'ldlms',
fields: ['id', 'title', 'content'],
contentType: 'sfwd-courses',
id
})
// Setup periodic background refresh
const refreshInterval = setInterval(() => {
refresh()
}, 30000) // Refresh every 30 seconds
// Cleanup on component unmount
onUnmounted(() => {
clearInterval(refreshInterval)
})
return data
}
// Example usage with automatic background updates
const courseId = ref('123')
const course = await useCourse(courseId.value)
</script>
<template>
<div>
<div v-if="isLoading">Loading...</div>
<div v-else>
<!-- This will automatically update when new data arrives -->
<div>Course Title: {{ course?.title }}</div>
<div>English Courses: {{ coursesEn.length }}</div>
<div>German Courses: {{ coursesDe.length }}</div>
</div>
</div>
</template>
interface LearndashOptions {
language: 'en' | 'de'
}
interface WordpressDataParams {
ep: string
fields: string[]
contentType: string
id?: number | string
}
export const useLearndashCache = () => {
const config = useRuntimeConfig()
// Global state management
const coursesEn = useState<any[]>('coursesEn', () => [])
const coursesDe = useState<any[]>('coursesDe', () => [])
const isLoading = useState<boolean>('dataCache-loading', () => false)
const getCacheKey = (language: string, contentType: string, id?: string | number) =>
`learndash-${language}-${contentType}-${id || 'all'}`
const createLearndashAPI = (options: LearndashOptions) => {
const endpoint = computed(() =>
options.language === 'en' ? config.public.wpEndpointEn : config.public.wpEndpointDe
)
const getWordpressData = async ({ ep, fields, contentType, id }: WordpressDataParams) => {
const cacheKey = getCacheKey(options.language, contentType, id)
// Use stale-while-revalidate pattern with useAsyncData
const { data, error, refresh } = await useAsyncData(cacheKey, async () => {
const response = await $fetch(`${endpoint.value}/wp-json/${ep}/v2/${contentType}${id ? `/${id}` : ''}`, {
params: {
per_page: 100,
_fields: fields.join(',')
},
headers: {
// Add your headers here
}
})
return response
}, {
server: false,
transform: (data) => Array.isArray(data) ? data : [data],
watch: [endpoint],
// Enable SWR behavior
immediate: true,
// Use cached data immediately while fetching new data
default: () => {
const existingData = useNuxtData(cacheKey)
return existingData.data.value || []
}
})
if (error.value) {
console.error(`Error fetching ${contentType}:`, error.value)
}
// Start background refresh for SWR
if (!error.value) {
setTimeout(() => {
refresh()
}, 0)
}
return { data, refresh }
}
const getCourses = () => {
return getWordpressData({
ep: 'ldlms',
fields: ['id', 'title', 'content'],
contentType: 'sfwd-courses'
})
}
// Force refresh specific data
const refreshData = async (params: WordpressDataParams) => {
const cacheKey = getCacheKey(options.language, params.contentType, params.id)
clearNuxtData(cacheKey)
return getWordpressData(params)
}
return {
getCourses,
getWordpressData,
refreshData
}
}
const learndashEn = createLearndashAPI({ language: 'en' })
const learndashDe = createLearndashAPI({ language: 'de' })
const refreshCourses = async () => {
isLoading.value = true
try {
const [{ data: enCourses }, { data: deCourses }] = await Promise.all([
learndashEn.getCourses(),
learndashDe.getCourses()
])
coursesEn.value = enCourses.value || []
coursesDe.value = deCourses.value || []
} catch (error) {
console.error('Error refreshing courses:', error)
} finally {
isLoading.value = false
}
}
// Initialize data with SWR pattern
onMounted(async () => {
if (!coursesEn.value.length || !coursesDe.value.length) {
await refreshCourses()
}
})
return {
coursesEn,
coursesDe,
isLoading,
refreshCourses,
learndashEn,
learndashDe
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment