I feel like I'm getting most of mobx, but I want to clarify something. I've got a store with some observables, the core of which is an array of objects (typescript):
class ClientStore {
constructor() {
this.loadClients();
}
@observable private _clients: IClient[] = [];
@computed get clients() {
return this._clients;
}
@observable isFetching: boolean = false;
@observable sortField: 'title' | 'modified' = 'modified';
@observable sortDescending: boolean = true;
getClientByUrlName(urlName: string): IClient {
return this._clients.find(c => c.urlName === urlName);
}
etc...
My question is that last function - getClientByUrlName. Since that's finding from an observable, any @observer react component that's using that function re-renders correctly. Is this idiomatic mobx for something like that? It feels like that should be a computed value. Should I make is a computed value in the component that wants to use it?
//import singletone ClientStore
class ClientDetailsView extends React.Component<{params:{urlName:string}}, void> {
@computed get client() {
return ClientSotre.clients.find(c => c.urlName === this.props.params.urlName);
}
...rest of react component
I'm looking for best practices and gotchas here. Any help is appreciated.
*edit fixed code sample error
In principle @computed
is simple a directive that tells MobX: "this value could be cached until any of the observables that is used changes". So in fact they can always be left out, it will just mean that your app will recompute more, but it doesn't alter the results.
So if you are missing @computed
on the function that is in principle not a problem in most cases. If it is, you can use createTransformer
which takes a one-argument function and builds a (self cleaning) memoization cache of computed values. But it is a little bit more involved, so actually your solution to introduce a computed property in your ClientDetailsView
is nicer. I would indeed recommend doing that as long as you have a nice place to put that computed property (the component that needs it in this case)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With