Pinia alert: The function "getActivePinia()" was invoked without an active Pinia instance. Could it be possible that you overlooked installing Pinia?

Despite having an action that dynamically updates the 'pending' state based on whether the data has been fetched, reactivity seems to be non-functional when used inside the component. This issue is referenced in the official Pinia documentation: . Attempting to make the 'pending' state reactive using storeToRefs resulted in the following error message:

Uncaught Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?
    const pinia = createPinia()
    app.use(pinia)
This will fail in production.

The code snippet for my Pinia store:

import { defineStore, storeToRefs } from 'pinia';

export const useStoreRecipes = defineStore('storeRecipes', {
    state: () => {
        return {
            data: [],
            pending: false,
        };
    },
    actions: {
        async loadRecipes() {
            try {
                this.pending = true;
                const res = await fetch('/api/recipe');
                if (res.ok) {
                    const data = await res.json();
                    this.data = data;
                } else {
                    console.error('Error: ', res.status, res.statusText);
                }
            } catch (err) {
                console.error(err);
            } finally {
                this.pending = false;
            }
        },
    },
});

const store = useStoreRecipes();

export const { pending } = storeToRefs(store);

My main.js file:

import '@/assets/scss/main.scss';
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import router from '@/router';
import App from './App.vue';

const app = createApp(App);
const pinia = createPinia();

app.use(pinia);
app.use(router);
app.mount('#app');

I then utilize the 'pending' property in one of my components.

<template>
    <Swiper
        class="swiper"
        :breakpoints="swiperOptions.breakpoints"
        :pagination="{
            clickable: true,
        }"
        :loop="true"
        :modules="swiperOptions.modules">
        <template v-for="recipe in storeRecipes.data" :key="recipe.id">
            <SwiperSlide class="swiper__slide">
                <ItemCard :data="recipe" :pending="storeRecipes.pending" />
            </SwiperSlide>
            <div class="swiper-custom-pagination"></div>
        </template>
    </Swiper>
</template>

<script setup>
import { onMounted } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Pagination } from 'swiper/modules';
import 'swiper/css/free-mode';
import 'swiper/css/pagination';
import 'swiper/css';
import { useStoreRecipes } from '@/stores/recipes/storeRecipes.js';

import ItemCard from '@/components/ItemCard.vue';

const storeRecipes = useStoreRecipes();

onMounted(async () => {
    await storeRecipes.loadRecipes();
});
</script>

How can I resolve this issue?

UPDATE:

The error has been resolved, but the 'pending' state still doesn't behave reactively. In this scenario where props are passed to the child component during skeleton loading, the skeleton loads continuously:

<template>
    <div class="card">
        <div class="card__item">
            <ItemCardSkeleton v-if="!pending" />
            <template v-else>
                <img
                    class="card__image"
                    :src="getSrc('.jpg')"
                    :alt="data.alt"
                    width="15.625rem" />
                <div class="card__content">
                    <h2 class="card__title">{{ data.title }}</h2>
                    <p class="card__text">{{ data.text }}</p>
                    <router-link class="card__link" :to="{ name: 'Home' }"
                        >View more</router-link
                    >
                </div>
            </template>
        </div>
    </div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import ItemCardSkeleton from '@/components/SkeletonLoaders/ItemCardSkeleton.vue';

const props = defineProps(['data', 'pending']);

const isLoaded = ref(false);

const getSrc = ext => {
    return new URL(
        `../assets/images/recipe/${props.data.image}${ext}`,
        import.meta.url
    ).href;
};

onMounted(() => {
    const img = new Image(getSrc('.jpg'));
    img.onload = () => {
        isLoaded.value = true;
    };
    img.src = getSrc('.jpg');
});
</script>

Answer №1

It is recommended to remove this code snippet from your store settings

const store = useStoreRecipes();

export const { pending } = storeToRefs(store);

While the approach is interesting, it appears to be ineffective. The pinia instance is not currently active. It is advisable to destructure refs directly in your component code:

<script setup>
import { useStoreRecipes } from '@/stores/recipes/storeRecipes.js';
import { storeToRefs } from 'pinia';

const storeRecipes = useStoreRecipes();

const { pending } = storeToRefs(store);
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to generate onsen-ui popover

My expertise lies in utilizing the Monaca platform for developing mobile applications using Onsen UI and AngularJS. I am looking to incorporate a popover feature from Onsen into my app, and have tried the following code snippet: angular.module('app& ...

Unexpected interactions between Socket.io and React using hooks

Currently, I am delving into the world of Socket.io with React utilizing Hooks. My goal is to create a timer that starts upon pressing the start button, and then every second, send the current time in the state to the server using socket.io. The server co ...

How can I show the table row as an inner table row when the first field is identical?

<tr ng-model="check" ng-repeat="orderBook in orderBookDetails| orderBy: 'orderBook.no'" value='check=$scope.orderBookDetails.sowNo'> <td ng-if='check!=orderBook.no'>{{orderBook.no}}</td> <td>{{order ...

Issue with Vue Loading Overlay Component functionality in nuxt2 .0

I've integrated the vue-loading-overlay plugin into my project. plugins/vueloadingoverlaylibrary.js import Vue from 'vue'; import Loading from 'vue-loading-overlay'; // import 'vue-loading-overlay/dist/vue-loading.css'; ...

The word 'function' is not defined in this React Component

Recently delving into the world of React, I decided to create a simple timer application. However, I encountered an error message upon running the code: (Line 40: 'timeDisplay' is not defined no-undef) class Home extends React.Component { ...

Is it possible for jQuery UI Autocomplete to utilize values from various input fields simultaneously?

I've hit a roadblock with this code and it's been giving me trouble for some time now. Here is the current state of my auto-complete script: jQ19(function(){ // minLength:1 - how many characters user enters in order to start search jQ19 ...

What are some ways to change the appearance of a component using its parent?

In order to make changes to the CSS properties of a Vue component from its parent, effectively overriding any existing styles within the component, I am seeking a solution. Initially, I assumed that styling a component like <my-component> directly f ...

Creating distinctive ng-form tags within a form using ng-repeat in Angular

I need help with creating a form that includes a table looping over a list of objects. Each object should have checkboxes for the user to check/uncheck attributes. The issue I am facing is setting the ng-model attribute on the checkboxes. This is what my ...

Prevent all click and keyup events from being activated until the ajax call finishes

Is there a way to prevent all links from being activated until an ajax call is complete? I am looking for a solution that works for both click events and keyup triggers. In essence, what I am after is: - The Ajax link is activated (either through a clic ...

Encountering event binding errors with Vue application connected to Netlify form

My goal is to hide/show a div based on the value of a form input. I was able to achieve this successfully with a standard form, but when I tried implementing it using netlify-forms, I encountered the following error: Unhandled promise rejection TypeError: ...

Error with replacing regular expressions in IE11 for the variable $0

Having both a string and a message: str = "Test $0 $1 $2"; message = "Hi %2 Hello %2" ; The goal is to replace all occurrences of %2 with str in the message using RegExp, like so: message = message.replace(new RegExp("%2" , "g"), str); While this works ...

Include quotation marks around a string in C# to convert it into JSON format

I am utilizing a service that operates with JSON format. However, the JSON data I am receiving does not include double quotes around keys and values. Here is an example of the data I have: [{name:{buyerfirstname:Randy, buyermiddlename:null, buyerlastnam ...

watchWebpack is compiling all the files

As per the webpack documentation on watching files webpack can keep an eye on files and recompile them whenever there are changes. My understanding is that this implies webpack will only compile the files that have been modified. I have a configuratio ...

Displaying the size of a JSON array in Vue.js

When working on my Vue.js project, I encountered an issue. I wanted to display the length of specific data from an API. However, when I used the code below, the status sold length appeared as 5 repeated five times instead of just once with a value of 5. ...

Create a variety of unique images without using the same one more than once

I'm currently developing my first Javascript game, but I've hit a roadblock.. I am trying to create a game that displays random images without repeating them. Each image should be accompanied by a random number between 4 and 10. The code I have w ...

Struggling to implement a seamless scrolling effect using CSSTransition Group

In my quest to achieve a smooth vertical scroll effect for content appearing and disappearing from the DOM, I've turned to CSSTransitionGroup (or ReactTransitionGroup). While I'm familiar with CSS animations for such effects, I need to implement ...

Exploring the CSS scale transformation alongside the Javascript offsetHeight attribute

After combining offsetHeight with scale transformation, I experienced a strange result. Below is my simple HTML code: <body> <div id="id01"> Some Text </div> <div id="id02" style="transform-origin: left top; transf ...

Steps to inject HTML content via id using a technology such as AngularJS' ng-include

My current project involves using AngularJS to compile a directive into the main page. This directive contains a series of buttons that dynamically change based on its internal state. I am interested in relocating these buttons to a menu-bar within the pag ...

Retrieving posts from a Facebook page by utilizing the FB API

Throughout the previous summer, I managed a website (not my own) that pulled in posts from its corresponding Facebook page and displayed them on a designated page. I utilized an application token for this process, but now it no longer functions due to the ...

Sending "item" properties to the "Route" element

I am looking for a way to dynamically pass a list of route objects as props for the Route components in my AppRouter component. Currently, I have the routes defined like this: export const routes = [ { path: '/about', element: About, exact: tru ...