lazyObservable
lazyObservable
creates an observable around a fetch
method that will not be invoked until the observable is needed the first time. The fetch method receive a sink
callback which can be used to replace the current value of the lazyObservable
. It is allowed to call sink
multiple times to keep the lazyObservable
up to date with some external resource.
Note:
It is the
current()
call itself which is being tracked by MobX, so make sure that you don't de-reference too early.
Parameters
fetch
initialValue
(T
): Will be returned fromcurrent
as long as thesink
has not been called at least once (optional, default:undefined
)modifier
Examples
const userProfile = lazyObservable(
sink => fetch("/myprofile").then(profile => sink(profile))
)
// use the userProfile in a React component:
const Profile = observer(({ userProfile }) =>
userProfile.current() === undefined
? <div>Loading user profile...</div>
: <div>{userProfile.current().displayName}</div>
)
// triggers refresh the userProfile
userProfile.refresh()