React observing

Mandatory properties

Mandatory properties

Overview

We use mandatory properties because a useObserver cannot listen for state changes on a property that can be undefined.

For useObserver to work correctly, the object passed as a parameter must have an id, a subscribe method, and a value property. These attributes are for useObserver to be able to subscribe to value changes.

Properties in a observable

If you want the hooks to work correctly, you will need to provide an object that has the properties below.

1const observableValue = observe('')
2
3// This observableValue has this props
4
5{
6 // The identifier of the state, this id is auto generated
7 id: '..uuid...',
8 // The value stored,
9 value: '',
10 // A function that allows you to add listeners on value changes.
11 subscribe: (call...) => ...,
12}

How to manage state without undefined properties?

You can actually have undefined properties. The value that is within the observable can be of any possible type. See the example:

If you are using typescript, just follow the examples below. If it's in javascript, you don't need to pass the typing, at any time assign the value you want.

// string or undefined
const myObservableValue = observe<string | undefined>('')
const myObservableValue = observe<string | undefined>(undefined)
// number or undefined
const myObservableValue = observe<number | undefined>(0)
const myObservableValue = observe<number | undefined>(undefined)
// any
const myObservableValue = observe<any>(0)
const myObservableValue = observe<any>(undefined)

Simple object to object with states

Object with undefined property:

const myObject = {
prop1: 'Value 1'
prop2: undefined as undefined | string
}

Now, object with state in properties:

const myObject = {
prop1: observe('Value 1')
prop2: observe(undefined) as IObservable<undefined | string>
}
Edit this page on GitHub