Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Server side data fetching using 'redux-saga'
import { fork } from 'redux-saga';
import fetchEntitySaga from './fetchEntitySaga';
export default prefetch(
({ getState }) => {
if (needsFetching(getState())) {
return fork(fetchEntitySaga, getState, ...args);
}
}
)(Component);
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));
}
}
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...
}
}
// ...
}
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