Skip to content

Commit

Permalink
fix:#523 - tanstack testings
Browse files Browse the repository at this point in the history
  • Loading branch information
marclupanc committed Dec 7, 2024
1 parent 76c9266 commit ac210fe
Show file tree
Hide file tree
Showing 6 changed files with 153 additions and 72 deletions.
10 changes: 8 additions & 2 deletions src/components/Admin/ManagePromptsEntries.vue
Original file line number Diff line number Diff line change
Expand Up @@ -437,8 +437,6 @@ function cantUnselect() {
$q.notify({ type: 'negative', message: "You can't unselect month prompt. Please choose another one first" })
}
promptStore.getTotalPromptsCount()
const confirmChangeMonthPrompt = () => {
updatePrompt.mutate(
{
Expand All @@ -457,6 +455,14 @@ const confirmChangeMonthPrompt = () => {
}
)
}
promptStore.getTotalPromptsCount()
// if (prompts.value.length !== 0) {
promptStore.listenForNewPrompts()
promptStore.listenForUpdatedPrompts()
promptStore.listenForDeletedPrompts()
// }
</script>
<style scoped>
.custom-table {
Expand Down
23 changes: 21 additions & 2 deletions src/components/Admin/PromptCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,25 @@ const { mutate } = useMutation({
pages: updatedPages
}
})
queryClient.setQueryData([QueryKeys.MONTH_PROMPT], (oldData) => {
if (!oldData || !oldData[0]) return oldData
const monthPrompt = oldData[0]
if (monthPrompt.id === updatedPrompt.id) {
return [
{
...monthPrompt,
categories: updatedPrompt.categories,
slug: updatedPrompt.slug,
title: updatedPrompt.title,
image: updatedPrompt.image,
description: updatedPrompt.description,
showcase: updatedPrompt.showcase
}
]
}
return oldData
})
},
retry: 3
})
Expand All @@ -348,8 +367,8 @@ async function onSubmit() {
return
}
if (!promptStore.getPrompts) {
const hasPrompt = await promptStore.hasPrompt(prompt.date, prompt.title, prompt.slug, !!props.id)
if (hasPrompt) {
// const hasPrompt = await promptStore.hasPrompt(prompt.date, prompt.title, prompt.slug, !!props.id)
if (false) {
return
}
} else if (
Expand Down
5 changes: 4 additions & 1 deletion src/pages/IndexPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<section class="text-center">
<h2 class="q-my-md text-h6">Welcome to Celebrity Fanalyzer!</h2>
<RouterLink to="month">
<q-responsive :ratio="1" :style="{ backgroundImage: `url(${data?.[0].image})`, borderRadius: '300px' }">
<q-responsive :ratio="1" :style="{ backgroundImage: `url(${data?.[0]?.image})`, borderRadius: '300px' }">
<div class="bg-blur flex">
<q-img
fit="contain"
Expand Down Expand Up @@ -232,6 +232,9 @@ const { data } = useQuery({
enabled: true,
staleTime: 5 * 24 * 60 * 60 * 1000
})
const something = useQuery({ queryKey: [QueryKeys.MONTH_PROMPT] })
console.log(something, '')
promptStore.checkNewMonthPrompt()
</script>

Expand Down
12 changes: 8 additions & 4 deletions src/pages/PromptPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import { startTracking, stopTracking } from 'src/utils/activityTracker'
import { useEntryStore, useErrorStore, useLikeStore, usePromptStore, useShareStore, useStatStore, useUserStore } from 'src/stores'
import { computed, onMounted, onUnmounted, ref, watch, watchEffect } from 'vue'
import { onBeforeRouteLeave, useRouter, useRoute } from 'vue-router'
import { useInfiniteQuery, useQuery } from '@tanstack/vue-query'
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/vue-query'
import { QueryKeys } from 'src/utils/query-keys'
const router = useRouter()
Expand All @@ -68,12 +68,13 @@ const editPrompt = ref({})
const params = computed(() => router.currentRoute.value?.params)
const { data: monthPrompt } = useQuery({
queryKey: [QueryKeys.MONTH_PROMPT],
queryFn: () => promptStore.fetchMonthPrompt,
queryFn: promptStore.fetchMonthPrompt,
// 5 days
refetchInterval: 5 * 24 * 60 * 60 * 1000,
enabled: true,
staleTime: 5 * 24 * 60 * 60 * 1000
})
const queryClient = useQueryClient()
const { data: allPrompts } = useInfiniteQuery({
queryKey: [QueryKeys.ALL_PROMPTS],
queryFn: ({ pageParam = null }) => promptStore.fetchPromptsInfinite({ pageParam }),
Expand All @@ -85,10 +86,12 @@ const { data: allPrompts } = useInfiniteQuery({
refetchInterval: 5 * 24 * 60 * 60 * 1000,
keepPreviousData: true
})
const loadedPrompts = computed(() => {
return allPrompts?.value?.pages.flatMap((page) => page.prompts) || []
})
const asdf = queryClient.getQueryData([QueryKeys.MONTH_PROMPT])
console.log(asdf, '')
const prompt = computed(() => {
if (route.name === 'month') {
Expand Down Expand Up @@ -198,6 +201,7 @@ onUnmounted(async () => {
window.removeEventListener('scroll', onScroll)
})
promptStore.checkNewMonthPrompt()
</script>
<style scoped lang="scss">
Expand Down
31 changes: 20 additions & 11 deletions src/pages/SearchPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,18 @@ const { data, isLoading, isFetchingNextPage, hasNextPage, fetchNextPage } = useI
queryKey: [QueryKeys.ALL_PROMPTS],
queryFn: ({ pageParam = null }) => promptStore.fetchPromptsInfinite({ pageParam }),
getNextPageParam: (lastPage) => {
const lastVisibleId = lastPage.lastVisible?._document?.data.value.mapValue.fields.id.stringValue
return lastVisibleId || null
if (lastPage?.lastVisible?._document?.data?.value?.mapValue?.fields?.id?.stringValue) {
return lastPage.lastVisible._document.data.value.mapValue.fields.id.stringValue
}
return null
},
staleTime: 5 * 24 * 60 * 60 * 1000,
refetchInterval: 5 * 24 * 60 * 60 * 1000,
keepPreviousData: true
cacheTime: 10 * 24 * 60 * 60 * 1000,
refetchInterval: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
keepPreviousData: true,
refetchOnMount: false
})
const updateSearchDate = (value) => {
Expand All @@ -158,28 +164,28 @@ const updateSearchDate = (value) => {
watch(search, async (newSearch) => {
if (newSearch.trim()) {
await fetchNextPage({ pageParam: null })
await fetchNextPage()
} else if (!newSearch.trim() && !isLoading.value && hasNextPage.value) {
await fetchNextPage({ pageParam: null })
await fetchNextPage()
}
if (hasNextPage.value) {
if (newSearch.trim()) {
await fetchNextPage({ pageParam: null })
await fetchNextPage()
}
}
})
watch(searchDate, async (newSearch) => {
if (newSearch.trim()) {
await fetchNextPage({ pageParam: null })
await fetchNextPage()
} else if (!newSearch.trim() && !isLoading.value && hasNextPage.value) {
await fetchNextPage({ pageParam: null })
await fetchNextPage()
}
if (hasNextPage.value) {
if (newSearch.trim()) {
await fetchNextPage({ pageParam: null })
await fetchNextPage()
}
}
})
Expand All @@ -195,8 +201,11 @@ onMounted(async () => {
}
})
promptStore.listenForNewPrompts()
promptStore.listenForUpdatedPrompts()
promptStore.listenForDeletedPrompts()
onUnmounted(() => {
promptStore.listenForNewPrompts()
advertiseStore.reset()
})
</script>
Expand Down
144 changes: 92 additions & 52 deletions src/stores/prompts.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import {
import { Notify } from 'quasar'
import { currentYearMonth } from 'src/utils/date'
import { QueryKeys } from 'src/utils/query-keys'
import { useQueryClient } from '@tanstack/vue-query'
import { useMutation, useQueryClient } from '@tanstack/vue-query'

let updatedBefore = false
const getPrompts = async (querySnapshot, userStore) => {
Expand Down Expand Up @@ -103,42 +103,82 @@ export const usePromptStore = defineStore('prompts', {
onSnapshot(promptsQuery, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
const newPrompt = change.doc.data()

const currentPrompts = queryClient.getQueryData([QueryKeys.ALL_PROMPTS])

if (currentPrompts) {
const promptExists = currentPrompts.pages[0].prompts.some((prompt) => prompt.id === newPrompt.id)

if (!promptExists) {
const updatedPrompts = [newPrompt, ...currentPrompts.pages[0].prompts]

queryClient.setQueryData([QueryKeys.ALL_PROMPTS], {
...currentPrompts,
pages: [
{
...currentPrompts.pages[0],
prompts: updatedPrompts
},
...currentPrompts.pages.slice(1)
]
})
queryClient.invalidateQueries([QueryKeys.ALL_PROMPTS])
}
})
})
},

listenForUpdatedPrompts() {
const queryClient = useQueryClient()
const promptsQuery = query(collection(db, 'prompts'))
onSnapshot(promptsQuery, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'modified') {
const updatedPrompt = change.doc.data()
const cachedPrompts = queryClient.getQueryData([QueryKeys.ALL_PROMPTS])
const monthPrompt = queryClient.getQueryData([QueryKeys.MONTH_PROMPT])

if (!cachedPrompts || !cachedPrompts.pages) return

const allPrompts = cachedPrompts.pages.flatMap((page) => page.prompts) || []
const promptExists = allPrompts.some((prompt) => prompt.id === updatedPrompt.id)

if (promptExists) {
if (monthPrompt && updatedPrompt.id === monthPrompt[0].id) {
// queryClient.setQueryData([QueryKeys.MONTH_PROMPT], { ...monthPrompt, updatedPrompt })
queryClient.invalidateQueries([QueryKeys.ALL_PROMPTS, QueryKeys.MONTH_PROMPT])
}
} else {
queryClient.setQueryData([QueryKeys.ALL_PROMPTS], {
pages: [
{
prompts: [newPrompt],
nextPage: null
}
]

// const updatedPrompts = allPrompts.map((prompt) =>
// prompt.id === updatedPrompt.id
// ? {
// ...prompt,
// categories: updatedPrompt.categories,
// slug: updatedPrompt.slug,
// title: updatedPrompt.title,
// image: updatedPrompt.image,
// description: updatedPrompt.description,
// showcase: updatedPrompt.showcase
// }
// : prompt
// )
// queryClient.setQueryData([QueryKeys.ALL_PROMPTS], {
// pages: [{ prompts: updatedPrompts }],
// pageParams: cachedPrompts.pageParams || []
// })
queryClient.invalidateQueries([QueryKeys.ALL_PROMPTS]).then((result) => {
console.log(result)
})
}
}
})
})
},

listenForDeletedPrompts() {
const queryClient = useQueryClient()
const promptsQuery = query(collection(db, 'prompts'))

onSnapshot(promptsQuery, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'removed') {
// const updatedPrompt = change.doc.data()
// const cachedPrompts = queryClient.getQueryData([QueryKeys.ALL_PROMPTS])
//
// if (!cachedPrompts || !cachedPrompts.pages) return
//
// const allPrompts = cachedPrompts.pages.flatMap((page) => page.prompts) || []
// const filteredPrompts = allPrompts.filter((prompt) => prompt.id !== updatedPrompt.id)
// queryClient.setQueryData([QueryKeys.ALL_PROMPTS], {
// pages: [{ prompts: filteredPrompts }],
// pageParams: cachedPrompts.pageParams || []
// })
queryClient.invalidateQueries([QueryKeys.ALL_PROMPTS])
}
})
})
},
async fetchMonthPrompt() {
const userStore = useUserStore()

Expand Down Expand Up @@ -270,29 +310,29 @@ export const usePromptStore = defineStore('prompts', {
}
},

async hasPrompt(date, title, slug, isEdit = false) {
try {
const promptSnapshot = await getDocs(
query(
collection(db, 'prompts'),
isEdit ? where('id', '!=', date) : '',
or(isEdit ? '' : where('date', '==', date), where('slug', '==', slug), where('title', '==', title))
)
)
promptSnapshot.docs.forEach((doc) => {
const data = doc.data()
if (data.title.toLowerCase() === title.toLowerCase() || data.slug === slug) {
Notify.create({ message: 'Prompt with this title already exists. Please choose another title.', type: 'negative' })
} else if (data.date === date) {
Notify.create({ message: 'Choose another month for this prompt.', type: 'negative' })
}
})
return !promptSnapshot.empty
} catch (error) {
console.log('Error occurred while checking', error)
return false
}
},
// async hasPrompt(date, title, slug, isEdit = false) {
// try {
// const promptSnapshot = await getDocs(
// query(
// collection(db, 'prompts'),
// isEdit ? where('id', '!=', date) : '',
// or(isEdit ? '' : where('date', '==', date), where('slug', '==', slug), where('title', '==', title))
// )
// )
// promptSnapshot.docs.forEach((doc) => {
// const data = doc.data()
// if (data.title.toLowerCase() === title.toLowerCase() || data.slug === slug) {
// Notify.create({ message: 'Prompt with this title already exists. Please choose another title.', type: 'negative' })
// } else if (data.date === date) {
// Notify.create({ message: 'Choose another month for this prompt.', type: 'negative' })
// }
// })
// return !promptSnapshot.empty
// } catch (error) {
// console.log('Error occurred while checking', error)
// return false
// }
// },

async getPromptDates() {
const set = new Set()
Expand Down

0 comments on commit ac210fe

Please sign in to comment.