diff --git a/src/widgets/Blog/__tests__/context.test.ts b/src/widgets/Blog/__tests__/context.test.ts index b1d344a..718603e 100644 --- a/src/widgets/Blog/__tests__/context.test.ts +++ b/src/widgets/Blog/__tests__/context.test.ts @@ -41,6 +41,8 @@ describe('blog Context', () => { const context = useProvidingPosts(mockLoader); expect(context.loading.value).toBe(true); + + await nextTick(); await nextTick(); expect(mockLoader).toHaveBeenCalled(); @@ -115,6 +117,8 @@ describe('blog Context', () => { it('should return available tags from all posts', async () => { const context = useProvidingPosts(mockLoader); + + await nextTick(); await nextTick(); const expectedTags = ['vue', 'javascript', 'frontend', 'typescript', 'react', 'comparison']; @@ -158,6 +162,7 @@ describe('blog Context', () => { const context = useProvidingPosts(errorLoader); await nextTick(); + await nextTick(); expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to load posts:', expect.any(Error)); expect(context.loading.value).toBe(false); diff --git a/src/widgets/Blog/context.ts b/src/widgets/Blog/context.ts index 48944cb..d195c08 100644 --- a/src/widgets/Blog/context.ts +++ b/src/widgets/Blog/context.ts @@ -1,7 +1,7 @@ import type { PostComment } from '@/entities/Comment'; import type { Post } from '@/entities/Post'; -import { useInjectionStore } from '@robonen/vue'; -import { computed, reactive, ref, shallowRef } from 'vue'; +import { useAsyncState, useInjectionStore } from '@robonen/vue'; +import { computed, reactive, shallowRef } from 'vue'; import { kmpSearch } from '@/shared/utils'; type PostItem = Post & { @@ -16,8 +16,22 @@ export const { useProvidingState: useProvidingPosts, useInjectedState: useInjectedPosts, } = useInjectionStore((loader: () => Promise) => { - const posts = shallowRef([]); - const loading = ref(false); + const { + state: posts, + isLoading: loading, + executeImmediately: loadPosts, + } = useAsyncState( + async () => { + const response = await loader(); + return response.data as PostItem[]; + }, + [], + { + onError(error) { + console.error('Failed to load posts:', error); + }, + }, + ); const selectedPost = shallowRef(null); @@ -54,21 +68,6 @@ export const { return Array.from(tagsSet); }); - const loadPosts = async () => { - loading.value = true; - - try { - const data = await loader(); - posts.value = data!.data as PostItem[]; - } - catch (error) { - console.error('Failed to load posts:', error); - } - finally { - loading.value = false; - } - }; - function toggleTag(tag: string) { if (filters.tags.has(tag)) filters.tags.delete(tag); @@ -85,9 +84,6 @@ export const { filters.tags.clear(); } - // Initial load - loadPosts(); - return { posts, loading,