Skip to content

Instantly share code, notes, and snippets.

@ntkoso
Last active January 17, 2018 08:20
Show Gist options
  • Save ntkoso/828c1b6baef8868648a0 to your computer and use it in GitHub Desktop.
Save ntkoso/828c1b6baef8868648a0 to your computer and use it in GitHub Desktop.
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