Skip to content

Commit ac38473

Browse files
committed
feat(Composables): Implement caching post logic
1 parent 4cb8521 commit ac38473

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/composables/posts.composable.js

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,31 @@
11
import { ref } from "vue";
22
import { useLoading } from "./loading.composable";
33
import PostsServices from "@/services/posts.services";
4+
import StorageService from "@/services/storage.service";
45

56
export default function useFetchPost() {
67
const { endLoading, isLoading, startLoading } = useLoading();
78

89
const post = ref(null);
910

1011
function fetchPost(id) {
11-
startLoading()
12-
return PostsServices.getOneById(id).then((response) => {
13-
post.value = response.data
14-
return response
15-
}).finally(()=>{
16-
endLoading()
17-
});
12+
const cachedPosts = StorageService.get("cached-posts") || {};
13+
if (cachedPosts[`post-${id}`]) return cachedPosts[`post-${id}`];
14+
startLoading();
15+
return PostsServices.getOneById(id)
16+
.then((response) => {
17+
post.value = response.data;
18+
StorageService.set('cached-posts', { ...cachedPosts, [`post-${id}`]: response.data })
19+
return response;
20+
})
21+
.finally(() => {
22+
endLoading();
23+
});
1824
}
1925

2026
return {
2127
postIsLoading: isLoading,
2228
post,
23-
fetchPost
29+
fetchPost,
2430
};
2531
}

0 commit comments

Comments
 (0)