Effects
In Ducky, effects manage side effects—operations interacting with external systems or involving asynchronous logic. They listen to actions dispatched to the store and dispatch new actions based on their outcomes, including API calls, notifications, logging, or timers.
What are Effects?
Effects handle asynchronous tasks and external interactions. Unlike reducers, which manage pure state transformations, effects:
Execute asynchronous API calls
Dispatch notifications and logs
Handle timers and delayed operations
Interact with external services or APIs
Two Types of Effects
Ducky provides two main approaches for defining effects:
1. Reactive Effects (ReactiveEffect
)
Reactive Effects are declarative and leverage observables to manage streams of actions:
This example:
Listens for
Increment
actions.Checks the current state; if the counter exceeds 15, waits 3 seconds.
Dispatches a
Reset
action afterward.
2. Async Effects (AsyncEffect<T>
)
Async Effects allow asynchronous handling with async/await
:
This example:
Handles an
Increment
action asynchronously.Checks state condition and delays execution accordingly.
Dispatches actions directly using the dispatcher.
Examples for Async Effects
Example: Asynchronous API Call
This example:
Performs an asynchronous API call.
Dispatches success or failure actions based on the outcome.
Example: Notifications after successful async operation
Key Characteristics of Effects
Asynchronous: Perform async tasks easily.
Dispatch Actions: Dispatch new actions based on task outcomes.
Separation of Concerns: Clearly separate state logic (reducers) from external interactions (effects).
Custom Operators (Reactive Effects Only)
Ducky simplifies Reactive Effect logic with custom operators:
OfType
: Filters actions by type.WithSliceState
: Combines actions with a specific state slice.InvokeService
: Handles API calls, dispatching success/failure actions automatically.
Best Practices
Single Responsibility: Keep each effect focused.
Leverage Custom Operators: Simplify Reactive Effect logic and enhance readability.
Handle Errors Explicitly: Dispatch meaningful actions upon failure.
Maintain Reducer Purity: Avoid side effects in reducers, using effects instead.