#Simple explicitly updating context values?

1 messages · Page 1 of 1 (latest)

hot salmon
#

I did my best on the title... Basically, in React Native I'm doing this a lot:

const machine = () => createMachine(...);

const Comp: React.FC<Props> = ({ route: { params: { routeValue }}}) => {
  const service = useInterpret(machine, {
    context: {
      routeValue,
    },
  });

  // a bunch of useSelector calls and such

  return <></>;
};

However, from what I understand the routeValue does not get updated in the machine context when it changes because I'm using a factory machine. This is easily solvable:

// add to machine root level
  on: {
    UPDATE_ROUTE_VALUE: {
      // I actually use named actions here
      actions: [assign({ routeValue: (_, {value}) => value })]
    },
  },

// and then add this to the component
useEffect(() => {
  service.send({type: 'UPDATE_ROUTE_VALUE', value: routeValue});
}, [routeValue]);

And that's what I've been doing, and it's especially useful as sometimes you want to respond differently when these values change (like go back to the initial state to reload everything). But that's a lot of code to add for any changeable context values, especially in the simple cases.

Am I missing something? Is there a Better Way? Thanks!

#

something I'm considering:

const machine = () => withUpdateable(createMachine(...), ['routeValue']);

// in the component
useUpdateable(service, 'routeValue', routeValue);

Though I'm worried this'll mess with the VSC extension or types (haven't tried it yet)