atlassian / react-sweet-state

Shared state management solution for React
https://atlassian.github.io/react-sweet-state/
MIT License
871 stars 55 forks source link

Ability to pass callback function during store creation for store initialisation and updates #186

Closed KennyYe closed 1 year ago

KennyYe commented 1 year ago

We would like the ability to pass in certain callback functions when stores are created that would track:

  1. Store initialisation
  2. Store changes
const onStoreInit = (storeInstance) => {
    // do something when store initialises
};

const onStoreUpdate = (storeInstance, actionDispatched) => {
    // do something when store updates
};

export const store = createStore({
    ...
    name: 'my-store',
    onStoreInit,
    onStoreUpdate,
});

This would allow us to implement custom logic into our stores changing without having to mount many useEffects to track and respond to these changes.

theKashey commented 1 year ago

Container has similar abilities, except onUpdate is triggered when container props are changed, not when it's state is updated.

You shall not be able to send a good message from a static function defined as a part of the store due to the absence of "context" and thus the necessity to communicate with other elements using globals. Can we do our best to use fewer globals?

KennyYe commented 1 year ago

Right hooking into createContainer would be a much better solution. perhaps there would be another option for onStoreUpdate as you mentioned that onUpdate only listens for changes to the container props.

albertogasparin commented 1 year ago

This has been merged as part of the improved Store/Container API #198 . Basically by using the new containedBy attribute on store creation you can provide additional handlers:

See docs. It will be available on v2.7.0+