I'm trying to follow along a Pinia tutorial and got stuck on this error: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?
I'm building a simple todo app in order to understand how Pinia works. I'm using Vue 3.2.13 and Pinia 2.1.4. I followed the steps described in the official Pinia documentation, but it doesn't seem to work.
This is my main.js file:
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
This is my App.vue file:
<template>
<main>
<input />
<button>Add</button>
<div v-for="todo in todos" :key="todo.id">
<strong>{{ todo.text }}</strong>
<button>Toggle</button>
</div>
</main>
</template>
<script>
import { useTodosStore } from '@/store/todos';
const { todos } = useTodosStore();
export default {
name: 'App',
data() {
return {
todos
};
},
};
</script>
And this is my store file, todos.js:
import { defineStore } from "pinia";
export const useTodosStore = defineStore('todos', {
state: () => ({
todos: [
{
id: 1,
text: 'Clean room',
isFinished: false,
},
],
}),
});
I was expecting to see it work, but I get a blank page instead and this error message in the console: Console error
Also, the app compiles without any issues: Compilation report
I tried to apply what I found in this answer, to no success.
What's wrong with my code?
useTodosStore
is a composable, a feature of Vue 3's Composition API, but your App.vue is written using Options API (Vue 2 API).
Composables and Options API are incompatible.
If you're not familiar with Composition API, consult the Vue 3 documentation and familiarize yourself with the syntax. Your App.vue written with Composition API could be written like so:
<script setup>
import { useTodosStore } from '@/store/todos';
import { storeToRefs } from 'pinia';
const store = useTodosStore();
const { todos } = storeToRefs(store)
</script>
It is recommended to use Pinia with Composition API but Options API is supported with the use of helpers like mapState
if you strongly prefer sticking with the older API
<script>
import { mapState } from 'pinia'
import { useTodosStore } from '@/store/todos';
export default {
computed: {
// read-only state
...mapState(useTodosStore, ['todos'])
// writable state
//...mapWritableState(useTodosStore, ['todos']),
},
}
</script>