Is this intentional?
When I declare a ref with default value inside a pinia defineStore (and then return it) when I access it from a component is always undefined, until I perform operations on it.
The store:
import {defineStore} from "pinia";
import {ref} from "vue";
export const useSelection = defineStore("selection", () => {
const contents = ref([]);
return {
contents
};
});
The component:
<script>
import { defineComponent, computed } from "vue";
import { useSelection } from "../store/selection.js";
export default defineComponent({
name: "Test",
setup() {
const selection = useSelection();
const thereIsSelection = computed(() => {
return selection.contents.value.length > 0;
})
return {
thereIsSelection
};
},
});
</script>
With this code I always get
Cannot read properties of undefined (reading 'length')
as selection.contents.value
is undefined
Is this normal? Best way to solve it? A computed instead of direct access to selection.contents
that returns an array if selection.contents
is undefined
?
You should do return selection.contents.length > 0;
instead of return selection.contents.value.length > 0;
const thereIsSelection = computed(() => {
return selection.contents.length > 0;
});
selection.contents
is the actual value you need, not a reference.