vue3 & typescript composables and returning array values

15 views Asked by At

New to Vue3 after a long time using Vue2. I have a composable file that returns an array of objects. In the browser dev tools, I can see my variable loaded with the correct data. However, any time I attempt to filter on this array, I get the error "favorites.filter is not a function". The only way I can access the array variables is seemingly to access "rawValue" which seems incorrect. What am i doing incorrectly?

composable:

import {onMounted, ref, watch} from 'vue';
import {Preferences} from "@capacitor/preferences";
import {useStore} from "@/store";

export const userFavorites = () => {

const FAVORITE_ARTISTS = 'favorites';
const favorites = ref({});
const store = useStore();

function addFavorite(artist, saved) {

    let payload = {
        artists: [artist],
        isFavorite: saved
    }

    store.dispatch({
        type: 'updateUserFavorites',
        payload
    });

    favorites.value.push(artist);
}

const loadFavorites = async () => {
    const favoriteList = await Preferences.get({key: FAVORITE_ARTISTS});

    const favoriteResults = favoriteList.value ? JSON.parse(favoriteList.value) : [];

    favorites.value = favoriteResults;
};

const cacheFavorites = () => {
    Preferences.set({
        key: FAVORITE_ARTISTS,
        value: JSON.stringify(favorites.value),
    });
};

onMounted(loadFavorites);
watch(favorites.value, cacheFavorites);

return {
    favorites,
    addFavorite
};
}

myfile.vue:

<script lang="ts" setup>
import {computed, ref} from "vue";
import RegisterToolbar from "@/components/RegisterToolbar.vue";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "@/store";
import {bookmarkOutline, bookmark} from 'ionicons/icons';
import {userFavorites} from '@/composables/userFavorites';
const {addFavorite, favorites } = userFavorites();

import {
  IonButton,
  IonBackButton,
  IonButtons,
  IonPage,
  IonIcon,
  IonContent,
  IonLabel,
  IonAvatar,
  IonCard,
  IonGrid,
  IonRow,
  IonCol,
  IonList,
  IonItem,
  IonCardHeader,
  IonChip,
  IonCardContent,
  IonSearchbar,
} from "@ionic/vue";

const store = useStore();
const router = useRouter();

const artists = computed(() => store.getters.getArtists);
const user = computed(() => store.getters.getUser);    
const route = useRoute();

function isFavorite(artist) {
  return favorites._rawValue.filter((favorite) => {
    return favorite.id === artist.id;
  }).length > 0;
}

const navigate = (url: string) => {
  router.push(url);
}
</script>
1

There are 1 answers

0
ArrayConstructor On

Your variable favorites isn't an array. You initialize it as an object.

const favorites = ref({});

->

const favorites = ref([]);

You need to adapt your code consequently.

Filter Method

Hope it helps ! :)