0 day streak
javascript / expert
Snippet

Algebraic Effects with Suspense Resource

This pattern simulates algebraic effects in React by throwing a promise. React catches this 'suspender' in the nearest Suspense boundary and retries the render once the promise resolves. This allows for synchronous-looking data fetching logic inside components.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function wrapPromise(promise) {
let status = 'pending';
let result;
let suspender = promise.then(
(r) => { status = 'success'; result = r; },
(e) => { status = 'error'; result = e; }
);
return {
read() {
if (status === 'pending') throw suspender;
if (status === 'error') throw result;
return result;
}
};
}
react
Breakdown
1
if (status === 'pending') throw suspender;
Throws the promise to signal React that the component is not ready to render yet.
2
if (status === 'error') throw result;
Throws the error so it can be caught by an Error Boundary.