Skip to content

Instantly share code, notes, and snippets.

@mutoo
Created December 13, 2019 13:13
Show Gist options
  • Save mutoo/d497b1783f03a4c0e1c97d4322aeb16c to your computer and use it in GitHub Desktop.
Save mutoo/d497b1783f03a4c0e1c97d4322aeb16c to your computer and use it in GitHub Desktop.
a promise bridge between react component and redux-saga.
// react.js
const SagaRequestDemo = () => {
const sagaRequest = useSagaRequest();
const loadUser = () => {
sagaRequest.dispatch(fetchUser({ id: 'mutoo' }))
.then((data) => {
console.log(`fetch user success: ${data}`);
})
.catch((err) => {
console.error(`fetch user failed: ${err}`);
});
};
const reset = () => { sagaRequest.reset() };
const { data, loading, err } = sagaRequest.status;
if (loading) return `fetching user`;
if (err) return <>
<pre>{`fetch user error: ${err}`}</pre>
<button onClick={reset}>reset</button>
</>;
return <>
<pre>{data}</pre>
<button onClick={loadUser}>load</button>
</>;
}
// saga.js
function* watch() {
yield takeEverySagaRequest(FETCH_USER, doFetchUser);
}
function* doFetchUser(action) {
const { id } = action.payload;
const { data } = yield fetch(`/users/${id}`);
yield put(storeUser({ user: data }));
return data; // for dispatched resolver
}
@mutoo
Copy link
Author

mutoo commented Dec 20, 2019

the serializableCheck will prevent redux dispatch a promise callback functions.
to solve this, we need to create a hash map registry to keep the promise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment