What is StoreContext
?
StoreContext
is based on the the Observer pattern which is used in numerous libraries: Redux, Zustand, Recoil, etc. => StoreContext
can replace Redux
, Zustand
, Recoil
completely with the built-in React features without installing any external libraries.
Example of StoreContext
: https://codesandbox.io/s/context-selector-demo-ifnqr5?file=/src/StoreContext.js
Usage in component
function SimpleComponent() {
const programId = 'id1';
const program = useStore((store) => store.programs[programId]);
const actions = useActions();
useEffect(() => {
actions.programs.fetch({ docId: programId });
}, [actions, programId]);
return <div>{program?.name}</div>;
}
More configs
Log functions
By default
console.error
is used for error log, setting window.StoreContextLogErrorFunc
for a custom error log
console.log
is used for info log, setting window.StoreContextLogFunc
for a custom info log
(see https://gitlab.com/fishbot/libs/context-selector/-/blob/master/src/StoreContext/utils/logStore.ts)
Default and additional callbacks
-
By default, onDone
, onError
, and onFinal
are the default callbacks for each action, e.g.
actions.programs.fetch({ docId: programId }, {
onDone: (doc) => {},
onError: (error) => {},
onFinal: () => {},
});
-
Additional callbacks can be passed to each action to the second param, e.g.
actions.programs.fetch({ docId: programId }, {
onCustomCallback: (payload) => {},
onAnotherCustomCallback: (anotherPayload) => {},
});
and then use it in the action definition, e.g.
const fetch = async ({ docId }, { dispatch, onCustomCallback, onAnotherCustomCallback }) => {
// do something, e.g. call to backend
const doc = await callBackend({ docId });
// dispatch something
dispatch({
type: types.update,
docId,
doc,
})
// then execute callbacks
if (someCondition) {
onCustomCallback(someData);
}
if (someAnotherCondition) {
onCustomCallback(someAnotherData);
}
}