How to make Reactive State
Reactive State refers to a state that changes according to a specific condition.
⚙️ Installation
$ npm install @cfcs/core
Reactive State
Reactive State
is a great extension for Vanilla
as well.
Because you can get properties that can be obtained from events in one Reactive State
.
If you can get properties through events you would use something like this:
// AS-IS
inst.on("event1", e => {
console.log(e.prop1);
});
inst.on("event2", e => {
console.log(e.prop1);
});
If you want to directly detect the state value, you can use it in the following way.
// TO-BE
inst.subscribe("prop1", nextValue => {
console.log(nextValue);
});
In this case, state detection is more intuitive than event detection.
- Class
ReactiveSubscribe
is a class decorator and adds.subscribe
and.unsubscribe
methods.Observe
is a property decorator and converts the property into areactive state
. You can detect its status through.subscribe
.
import { ReactiveSubscribe, Observe } from "@cfcs/core";
@ReactiveSubscribe
class Component {
@Observe value1 = 1;
constructor() {
requestAnimationFrame(() => {
this.value1 = 2;
});
}
}
interface Component extends ReactiveSubscribe<{
value1: number;
value2: number;
}> {}
const component = new Component();
// 1
console.log(component.value1);
component.subscribe("value1", nextValue => {
// When the change event occurs => (2, 2)
console.log(nextValue, component.value2);
});
- Inline Object
reactive
converts the object into a reactive object, and values can be changed through.subscribe
.
import { reactive } from "@cfcs/core";
const obj = reactive({
value1: 1,
});
// 1
console.log(obj.value1);
obj.subscribe("value1", nextValue => {
// When the change event occurs => (2, 2)
console.log(nextValue, obj.value1);
});
obj.value1 = 2;