Created
December 13, 2019 13:13
-
-
Save mutoo/d497b1783f03a4c0e1c97d4322aeb16c to your computer and use it in GitHub Desktop.
a promise bridge between react component and redux-saga.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.