useViewModelCache

Source
import { useViewModelCache } from "@prestojs/viewmodel";
useViewModelCache(viewModel,selector,args,isEquals)

Select some data out of the cache for use in a component. Whenever the cache data changes the component will re-render with latest value.

See ViewModelCache for more details on how to read data from the cache. The Field notation documentation goes over the possible formats for the fields argument.

Example usage:

function UserView({ id }) {
const record = useViewModelCache(User, cache => cache.get(id, ['firstName']));
return <div>Welcome {record.firstName}</div>;
}

Extra arguments can be passed through as a third argument to the selector which makes it easier to create reusable selectors. We could rewrite the above like:

const selectUser = (cache, id, fieldNames) => cache.get(id, fieldNames);
function UserView({ id }) {
const record = useViewModelCache(User, selectUser, [id, fieldNames]);
return <div>Welcome {record.firstName}</div>;
}

Selectors can return anything:

const usersByGroup = cache => cache.getAll(['groupId', 'firstName', 'email']).reduce((acc, record) => {
acc[record.groupId] = acc[record.firstName] || [];
acc[record.groupId].push(record);
return acc;
}, {})
function GroupedUserView() {
const groupedUsers = useViewModelCache(User, usersByGroup);
return ...
}

In the preceding example the object returned from useViewModelChange will change each time GroupUserView renders. This is because the selector returns a new object every time and internally useViewModelChange does a strict equality check to determine whether to return the new value or keep the old value. As an optimisation you can pass a third parameter that defines how to compare the previous and current value:

import isEqual from 'lodash/isEqual';
function OptimisedGroupedUserView() {
// isEqual does a deep equality check so if the underlying cached values remain the same then the
// object returned here will be the same across multiple renders.
const groupedUsers = useViewModelCache(User, usersByGroup, [], isEqual);
return ...
}
ParameterTypeDescription
*viewModelViewModel Class

The ViewModel to use the cache from

*selector
Function

A function that gets passed the cache and selects data from it. If your selector is slow consider using a library like reselect to create your selector with. Note that get, getAll and getList on ViewModelCache will return the same object across multiple calls if the underlying data has not changed.

*argsU

Any extra arguments to pass through to the selector. These will be compared shallowly and any changes will re-run the selector.

*isEquals
Function

Optionally control how equality is determined for an object. By default this is a strict equality check. This is useful as an optimisation when you want the value returned from a selector to be the same object when the selector re-runs.

ResultType

The data as returned by selector