-
-
Save ifokeev/043b4a3ae84857b809339790f02851eb to your computer and use it in GitHub Desktop.
Server side data fetching using 'redux-saga'
This file contains 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
import { fork } from 'redux-saga'; | |
import fetchEntitySaga from './fetchEntitySaga'; | |
export default prefetch( | |
({ getState }) => { | |
if (needsFetching(getState())) { | |
return fork(fetchEntitySaga, getState, ...args); | |
} | |
} | |
)(Component); |
This file contains 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
import { call, put } from 'redux-saga'; | |
import { fetchStart, fetchSuccess, fetchFailure } from './actions/entity'; | |
export default function *fetchEntitySaga(getState, ...args) { | |
yield put(fetchStart()); | |
try { | |
const result = yield call(fetch, ...args); | |
yield put(fetchSuccess(result)); | |
} catch (err) { | |
yield put(fetchFailure(err)); | |
} | |
} |
This file contains 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
import createReduxSagaMiddleware from 'redux-saga'; | |
import serverSaga from './serverSaga'; | |
export default async function serverMiddleware(ctx, next) { | |
// ... | |
const reduxSagaMiddleware = createReduxSagaMiddleware(); | |
const store = configureStore(state, [reduxSagaMiddleware]); | |
const locals = { getState: store.getState }; | |
// same way as react-fetcher / redial, but fetcher functions return 'fork' effects instead of promises. | |
const forks = collectSagaForks( | |
routerProps.components, | |
locals | |
); | |
if (forks.length > 0) { | |
try { | |
await reduxSagaMiddleware.run(serverSaga, forks).done; | |
} catch (err) { | |
// handle error... | |
} | |
} | |
// ... | |
} |
This file contains 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
import { join } from 'redux-saga'; | |
export default function *serverSaga(getState, forks: Array<ForkEffect>) { | |
const tasks = yield forks; | |
yield tasks.map(join); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment