Encountered a TypeScript typing error when retrieving data from the Pinia state to populate the template

Having a type error when trying to pass data from the Pinia store to a child component's input field using TypeScript -

Error message: 'Property 'storeForm' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: Partial<{}> & Omit<Readonly<ExtractPropTypes<{}>> & VNodeProps & AllowedComponentProps & ComponentCustomProps, never>; ... 10 more ...; $watch<T extends string | ((...args: any) => any)>(source: T, cb: T extends (...args: any) => infer R ? (args_0: R, args_1: R) => ...'.

Questioning if typing the store or other properties is necessary?

// Child component

<template>
  <v-sheet width="300" class="mx-auto">
      <v-form fast-fail @submit.prevent>
        <!-- v-model="firstName" -->
        <v-text-field
          label="First name"
          :rules="firstNameRules"
          placeholder="Your Name"
        >{{ storeForm.firstName }}</v-text-field>  // encountering error here
  
        <!-- v-model="lastName" -->
        <v-text-field
          label="Last name"
          :rules="lastNameRules"
        >{{ storeForm.lastName }}</v-text-field>
  
        <v-btn type="submit" block class="mt-2" @click="submit($event)">Submit</v-btn>
      </v-form>
    </v-sheet>
  </template>
<script lang="ts">
  import { ref } from 'vue'
  import {useForm} from '@/stores/form'
  import  router  from '../router'
  import { defineComponent } from 'vue'


  export default defineComponent({
  setup() {
    const storeForm = useForm();               
    const firstName = ref<string>('')
    const lastName = ref<string>('')
    const firstNameRules = ref<any>(
      (value: String)  => {
        if (value?.length > 3) return true
        return 'First name must be at least 3 characters.'
      }
    )
    const lastNameRules = ref<any>(
      (value: String) => {
          if (/[^0-9]/.test(String(value))) return true
          return 'Last name can not contain digits.'
        }
        )
        
        const submit = (event: Event) => {
          event.preventDefault();
          let user = {
            firstName: firstName.value,
            lastName: lastName.value,
          }
          storeForm.login(user)
          
          router.push('/');
          
          firstName.value = '';
          lastName.value = '';
        }
        return {firstName, lastName, firstNameRules, lastNameRules, submit};
  }
})
</script>

// Store file

import { defineStore } from 'pinia'

export const useForm = defineStore('login',{
  state: () => ({
    firstName: <string>'',             
    lastName: <string>''
  }),
  getters: {
  },
  actions: {
    login(data: any) {
      this.firstName = data.firstName
      this.lastName = data.lastName
    }
  }
})

Answer №1

Make sure to return the "storeForm" object from your setup function in order for it to be reactive.

For reactive data, consider using the suggested syntax in the documentation provided at the following link:

<script setup>
import { storeToRefs } from 'pinia'

const store = useCounterStore()
// `name` and `doubleCount` are now reactive refs
// This will also extract refs for properties added by plugins
// but skip any action or non reactive (non ref/reactive) property
const { name, doubleCount } = storeToRefs(store)
// You can easily destructure the increment action as well
const { increment } = 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

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Display only specific PHP-encoded JSON data in a formatted table

After receiving a variable from PHP, I convert it to JSON as shown below: var myData = <?php echo json_encode($json_array) ?>; When I log the output, it looks something like this: 0: Carat: "0.70" Clarity: "VVS2" Color: "D" Cut: "Very Good" Polish ...

The CSS cursor style is taking precedence over the inline cursor style while dragging items in the list

I am currently utilizing the Nestable JS library and have a list of nestable items in my tree. I am trying to implement a cursor: pointer when hovering over them and a cursor: move when dragging. However, I am facing issues in getting this functionality to ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

Error encountered while integrating AngularJS date picker

I am facing an issue while trying to set up the AngularJS date picker from this link. I am getting an error message that I don't quite understand. Could it be due to a missing library file or just syntax errors? var myApp = angular.module('myA ...

Using AngularJS to link a model referenced in the view (ng-bind) to a $resource obtained from an API

I'm currently facing a challenge in Angular where I need to establish a connection between a database object displayed in the html view and its corresponding instance through a json API. While I have a functioning api and $resource, I am struggling t ...

Experiencing difficulty importing Materialize CSS JS into React

Good day everyone, I've been facing challenges in implementing materialize css into my react-app, specifically with the JavaScript files. After trying various methods, I believe that I have made some progress using the following approach: In my &ap ...

What is the best method to ensure that none of the select option values are left empty?

I have a total of 5 select option drop down menus currently, but this number may increase in the future depending on requirements. The issue I'm facing is that when I select the last element, it returns true even though the other elements are empty. I ...

Sending data from an Angular form to a Node.js server using Sendgrid or Nodemailer

I recently implemented a solution from this example to send data from my Angular app to Node.js and then post a web form to Sendgrid. After making some adjustments, it is now working smoothly, and I am grateful for the quick start guide provided. The funct ...

Is it possible to bundle MongoDB into an Electron application?

Is it possible to include MongoDB in an Electron app to avoid having to install it on a client's computer? I am creating an application on OSX but it will most likely be used on Windows. Will the clients need to individually install Mongo themselves? ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

In Django, I am assigning the URL as the category but encountering an error that is expecting a semicolon in JavaScript

I am currently trying to set the category as the URL in Django but I am running into an error that states '; expected.javascript' {% for category in all_categories %} <div onclick="location.href='{% url 'category' categ ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Initiate Jquery Modal Using JavaScript

Currently, I am attempting to implement a jquery modal box from javascript, but I am facing some challenges. I have successfully set up a form verification process to check for empty fields and display a message accordingly. However, I am also interested i ...

Issue encountered with invoking carousel.to() method in Bootstrap 5

// Create a new carousel instance let car = new bootstrap.Carousel(document.querySelector('#carouselMenu'), { interval: 0, wrap: false }); // <SNIP> // Go to page at index 1 car.to("1"); Error: https://i.sstat ...

Leaving the "OK" button untouched in the sweet alert dialog

While implementing sweet alert in my project, I encountered an issue where the button text was not changing and the cancel button was missing on some pages. On certain pages, it only displayed OK. You can see a screenshot below for reference. https://i.s ...

Modify div content based on user selection

I have a question about updating the content of a div based on certain conditions in my code. Here is what I'm trying to achieve: <div class="form-control" ns-show="runningImport" disabled="disabled"> {{input[row.header_safe]}}{{select[row. ...

Ways to update state based on changes in localStorage values

Is there a way to update the state when the value of localStorage changes? For instance, I have a language switch button for French and English. When I click on English, it gets stored in localStorage. How can I ensure that the entire project switches to t ...

ACTUAL preventing a component from losing its focus

I have been exploring ways to effectively stop a DOM element from losing focus. While researching, I came across different solutions on StackOverflow such as: StackOverflow solution 1 StackOverflow solution 2 StackOverflow solution 3 However, these sol ...

A step-by-step guide on showcasing the content from a textfield onto a dynamic column chart

How can I show the value from a text field in a column chart? I found the code for the chart on this website(). I tried using the code below, but nothing happens. Can someone please assist me? <script> window.onload = function () { ...