Skip to content

Instantly share code, notes, and snippets.

@dsafonov-grid
Created March 1, 2023 15:55
Show Gist options
  • Save dsafonov-grid/e7adc60b543cb977faf6bdb30f2cea60 to your computer and use it in GitHub Desktop.
Save dsafonov-grid/e7adc60b543cb977faf6bdb30f2cea60 to your computer and use it in GitHub Desktop.
import CharacterService from "@/services/character";
import FavoritesService from "@/services/favorites";
export const state = {
characters: [],
character: null,
favorites: [],
meta: {},
};
export const namespaced = true;
export const mutations = {
SET_CHARACTERS: (state, payload) => {
state.characters = payload;
},
SET_FAVORITES: (state, payload) => {
state.favorites = payload;
},
SET_CHARACTER: (state, payload) => {
state.character = payload;
},
SET_META: (state, payload) => {
state.meta = payload;
},
};
export const actions = {
removeFromFavorites(context, character) {
const newFavorites = context.state.favorites.filter(
(fav) => fav.id !== character.id
);
FavoritesService.saveFavorites(newFavorites);
context.commit("SET_FAVORITES", newFavorites);
},
addToFavorites(context, character) {
const favorites = context.state.favorites;
FavoritesService.saveFavorites([...favorites, character]);
context.commit("SET_FAVORITES", [...favorites, character]);
},
initFavorites(context) {
const favorites = FavoritesService.fetchFavorites();
context.commit("SET_FAVORITES", favorites);
},
fetchCharacters(context, options) {
CharacterService.fetchCharacters(options)
.then((response) => {
context.commit("SET_CHARACTERS", response.data.results);
context.commit("SET_META", response.data.info);
})
.catch((err) => {
context.commit("SET_CHARACTERS", []);
context.commit("SET_META", {});
console.log(err);
});
},
fetchCharacter(context, id) {
const char = context.getters.getCharacterById(id);
if (char) {
context.commit("SET_CHARACTER", char);
} else {
CharacterService.fetchCharacter(id)
.then((response) => {
context.commit("SET_CHARACTER", response.data);
})
.catch((err) => {
console.log(err);
});
}
},
};
export const getters = {
getCharacterById: (state) => (id) => {
return state.characters.find((character) => character.id === id);
},
getFavoritesCount: (state) => {
return state.favorites.length;
},
isInFavorites: (state) => (id) => {
return state.favorites.find((fav) => fav.id === id);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment