#Derived context values

1 messages · Page 1 of 1 (latest)

covert rain
#

Is there a standard way of deriving context values from other values?

For example:

context: {
  items: [],
  sortedItems: [], // <-- derived value from `items`
}
livid osprey
#

You have to implicitly encode your assign actions so that when items is updated then sortedItems is updated.

covert rain
#

@livid osprey Thank you

wary moth
#

@covert rain

You can also use a selector.

const selectSortedItems = (ctx) => orderBy(ctx.items, "name")

Then, when consuming in a component (assuming you're using React),

const sortedItems = useSelector(state => {
  return selectSortedItems(state.context)
});

Note than you can also use the selector in the machine itself (in actions/guards).

Also, in order to prevent unnecessary work and only recalculate sortedItems when items have changed, you can use reselect:

import { createSelector } from "reselect";

const selectSortedItems = createSelector(
  [context => context.items], 
  items => orderBy(items, "name")
);

selectSortedItems(context); // calculate & cache
selectSortedItems(context); // items are the same - return from cache

See docs here: https://reselect.js.org/