Having difficulty setting up pinia stores in nuxt 3

Viewed 727

I'm currently trying to setup a project using nuxt 3 with pinia for state management and I have bumped into the following error:

[h3] [unhandled] H3Error: defineStore is not defined
    at createError (file:///home/johnr/Code/Personal/test/node_modules/h3/dist/index.mjs:191:15)
    at Server.nodeHandler (file:///home/johnr/Code/Personal/test/node_modules/h3/dist/index.mjs:381:21) {
  statusCode: 500,
  fatal: false,
  unhandled: true,
  statusMessage: 'Internal Server Error'
}

I initialized the project with npx nuxi init and then ran npm i, followed by npm install @pinia/nuxt. I then added pinia to nuxt.config.ts:

 // nuxt.config.js
    export default {
        // ... other options
        modules: [
            // ...
            '@pinia/nuxt',
        ],
    }

and created a basic store in store/counter.js:

 export const useCounterStore = defineStore('counter', () => {
  const count = ref(0);
  function increment() {
    count.value++;
  }

  return { count, increment };
});

and have tried to use the returned count in the app template:

<template>
  <div>
    <p>The count is {{ counterStore.count.value }}</p>
  </div>
</template>

<script setup>
import { useCounterStore } from './store/counter.js';
const counterStore = useCounterStore();
</script>
1 Answers

It looks like you forgot to import defineStore in store/counter.js:

import { defineStore } from 'pinia'

Related