Defining a store with TypeScript left me with questions about reactivity #1615
Answered
by
posva
JoostKersjes
asked this question in
Help and Questions
Replies: 1 comment
-
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
JoostKersjes
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Code
Problem
Accessing
store.property
in the<template>
will always giveundefined
and is not reactive.Why do I expect it to be reactive? When would I want to set a property that isn't described in the state?
I fell into this "trap" because I added a
StoreState
interface. I marked a property as optional with?:
. With that interface, I can initialize the store without setting a value for the property.Because I couldn't find any clear documentation on why my
store.property
wasn't reactive, I assumed that accessing properties like that just were never reactive. This assumption grew even stronger when I figured out that accessing it throughstore.$state.property
is reactive.Again, I couldn't find any clear documentation that accessing properties without going through
$state
are supposed to be reactive, so I changed pretty much all of the code where I access store properties to go through$state
, just in case.I realized after messing around for too long, that going through
$state
isn't required to have a reactive reference.Solution
To fix the problem of
store.property
not being reactive, you simply need to make sure the property exists in the initial state. The type definition can be changed fromproperty?: number;
toproperty: number | undefined;
to enforce this.My questions
undefined
?$state
?Beta Was this translation helpful? Give feedback.
All reactions