Search code examples
javascriptvue.jsvuejs3pinia

Conditionally accessing Pinia value from template in Vue 3


I'm trying to render a component only if the value accessed from my Pinia store is true -

// MessageArea.vue
import { useValidationStore } from '../../stores/ValidationStore.js'

data() {
        return {
            errors: {
                english: useValidationStore().english.error,
            },
        }
    },

<template>
  <p v-if="errors.english">
    <EnglishErrorMessage />
  </p>
</template>

By default, it is false -

import { defineStore } from "pinia";

export const useValidationStore = defineStore("validation", {
    state: () => {
        return {
            english: {
                input: '',
                error: false,
            },
        }
    }
})

I'm also accessing that same value from another file to check for the error -

<script>
import { useValidationStore } from '../../../stores/ValidationStore';

export default {
    data() {
        return {
            input: useValidationStore().english.message,
            error: useValidationStore().english.error,
        }
    },
    methods: {
        validate(input) {
            this.input = input.target.value
            const legalChars = /^[A-Za-z\s]*$/.test(this.input);
            if (!legalChars && this.input !== "") {
            this.error = true;
        } else if (this.input === "" || (legalChars && !legalChars)) {
            this.error = false;
            }
            console.log(this.error)
            console.log(this.input)
        }
    }
}
</script>

<template>
    <input
        @input="validate"
        :value="input"
    />
</template>

The console log values are updating reactively. Also, this.error will be logged as true when an illegal character is entered into the input. The reactivity is behaving as expected. So, I'm not sure why '' will not render in this case?

Am I not accessing the pinia value correctly in the template?

I've tried to understand what 'mapState()' and 'mapStores()' from the docs and if they can help me but I'm still confused.


Solution

  • You need to mutate the store state in validate method. If you want to use pinia in options api you can use mapState and mapWritableState in computed property to remain rective. Take a look here codesandbox please.