Composing Custom Effects
Use the core effects is meant to be easy. That's because they are composable, which means you could nest the effects inside each other. For example, if you want to run an action through a thunk and promise, you could easily write:
effects.thunk(() => (
effects.defer((resolve) => {
resolve(effects.act((state) => [state, effects.none()]);
})
))
Of course, if you do this frequently, it's probably a good time to wrap up the common pattern in a custom effect.
Let's start off with a larger effect, one that I actually wrote for a demo project, and we'll go through the refactoring steps I had to making this two composable and powerful effects.
noncomposableNotificationEffect.js
import { effects } from 'ferp';
export const notificationEffect = (title, body) => effects.defer(
Notification.requestPermission()
.then((result) => {
if (result === 'granted') {
const notification = new Notification(title, { body });
}
})
.catch(() => {})
.then(() => {
return effects.none();
});
);