useGlobal with nested state
Closed this issue · 2 comments
Hi there,
would it make sense to be able to invoke useGlobal with a nested property on the global state?
I mean something like this: useGlobal('complexProperty.simpleProperty');
or is the recommended way to always use a reducer in these cases?
Great work on this library by the way, it makes life incredibly easy, cheers!
-Roland
Currently, it is best to subscribe to the shallow key complexProperty
. That is because the shallow keys are not attached to a standard object like { x: 'y' }
. They are special objects that monitors when keys are accessed, in order to trigger a subscription to change.
Nested objects are not mutated this way. If you save { complexProperty: { simpleProperty: 'y' } }
to the state, we do not change { simpleProperty: 'y' }
at all. We could, but I fear it would cause more problems than it would solve, specifically when dealing with class instances.
If you save { complexProperty: new MyClass() }
should we mutate the MyClass
instance definition to allow subscriptions? If MyClass has a simpleProperty
member variable, should we be able to subscribed to it? I fear it risks breaking implementations of some MyClass
or test suites that expect the object retrieved from the state to match the one that was saved.
Because of this, it doesn't exist today. The best solution is to subscribe to complexProperty
and use simpleProperty
from there. You can also use a Provider to group related state:
const ComplexPropertyProvider = createProvider({
simpleProperty: 'y',
});
// ...
const [ simpleProperty, setSimpleProperty ] = ComplexPropertyProvider.useGlobal('simpleProperty');
A third option is to use the withGlobal
HOC to convert global -> some.nested.value
to just props -> value
.
I'm not strongly against nested properties, it's just finding a safe way to implement it.
Feel free to keep discussing it here. For cleanliness, I'll close this as a duplicate of issue #4.
Hey Charles,
you make some very clear points. I can use the provider approach for my cases, so thank you for your answers.