Search code examples
typescriptvue.jseslintpinia

Vue.js + Pinia: How can I solve problems found by ESLint and TypeScript?


I'm new to Vue.js + Pinia. I would like to know how to solve these messages.

  1. 'state:' is defined but never used.

The code below is @/stores/user.ts.

import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  state: () => {
    return {
      name: ''
    }
  }
})

enter image description here

  1. Property 'name' does not exist on type 'Store<"user", {}, {}, {}>'

This file is one of the vue files.

<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from '@/components/HelloWorld.vue'
import { useUserStore } from '@/stores/user';

const userStore = useUserStore()

</script>

<template>
  <header>
    < img alt="logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld :msg="userStore.name" />

      <nav>
        <RouterLink to="/">Home</RouterLink>
      </nav>
    </div>
  </header>

  <RouterView />
</template>

enter image description here


Solution

  • This is a tricky corner of JavaScript syntax - if an arrow function has curly braces, those are interpreted as the function body. In other words:

    () => {
      state: () => {
        return {
          name: ''
        }
      }
    }
    

    is similar to

    function () {
      state: () => {
        return {
          name: ''
        }
      }
    }
    

    and means "a function whose body consists of a labeled statement that declares an anonymous arrow function but never does anything with it."

    To return an object literal, add parentheses, to force the syntax to be an expression instead of a function body.

    export const useUserStore = defineStore('user', () => ({
      state: () => {
        return {
          name: ''
        }
      }
    }))