feat: add localstorage saving

This commit is contained in:
Sergey Krylov 2025-02-10 07:52:23 +03:00
parent 47485f941d
commit 7843804682
2 changed files with 67 additions and 51 deletions

View File

@ -1,28 +1,40 @@
import { defineStore } from 'pinia';
import { computed, ref, watch } from 'vue';
export const useMovieStore = defineStore('movieStore', {
state: () => ({
movies: [],
activeTab: 1,
}),
getters: {
watchedMovies: (store) => {
return store.movies.filter((el) => el.isWatched)
},
totalCount: (store) => {
return store.movies.length
export const useMovieStore = defineStore('movieStore', () => {
const movies = ref([]);
const activeTab = ref(1);
const moviesOnLocalStorage = localStorage.getItem('movies');
if (moviesOnLocalStorage) {
movies.value = JSON.parse(moviesOnLocalStorage)
}
},
actions: {
setActiveTab(tab) {
this.activeTab = tab
},
toggleWatchedMovie(id) {
const movie = this.movies.find((el) => el.id === id);
const watchedMovies = computed(() => movies.value.filter((el) => el.isWatched))
const totalCount = computed(() => movies.value.length);
const setActiveTab = (tab) => activeTab.value = tab;
const toggleWatchedMovie = (id) => {
const movie = movies.value.find((el) => el.id === id);
movie.isWatched = !movie.isWatched
},
removeMovie(id) {
this.movies = this.movies.filter((el) => el.id !== id)
};
const removeMovie = (id) => {
movies.value = movies.value.filter((el) => el.id !== id)
}
watch(movies, () => {
localStorage.setItem('movies', JSON.stringify(movies.value));
}, {deep: true})
return {
movies,
activeTab,
watchedMovies,
totalCount,
setActiveTab,
toggleWatchedMovie,
removeMovie,
}
})

View File

@ -1,37 +1,41 @@
import { defineStore } from 'pinia';
import { useMovieStore } from './movie-store.js';
import { ref } from 'vue';
const url = `https:api.themoviedb.org/3/search/movie?api_key=${import.meta.env.VITE_API_KEY}&query=`;
export const useSearchStore = defineStore('search-store', {
state: () => ({
movies: [],
timer: null,
loading: false,
}),
actions: {
async getMovies(search) {
export const useSearchStore = defineStore('search-store', () => {
const loading = ref(false);
const movies = ref([]);
const movieStore = useMovieStore();
const getMovies = async (search) => {
const request = async () => {
const res = await fetch(url + search);
const data = await res.json();
this.movies = data.results
movies.value = data.results
}
try {
clearTimeout(this.timer);
this.loading = true;
loading.value = true;
await request();
} catch (e) {
console.log('error', e);
} finally {
this.loading = false;
loading.value = false;
}
},
addToUserMovies(obj) {
const movieStore = useMovieStore();
}
const addToUserMovies = (obj) => {
movieStore.movies.push(obj);
movieStore.setActiveTab(1);
}
return {
getMovies,
addToUserMovies,
loading,
movies,
}
})