Vano
Vano

Reputation: 740

Should I run all saga when launch app?

I've just started to learn and use redux-saga, at first I thought it worked this way: first you make action which is connected to saga, then saga detects action,calls api which returns data and saga returns this data to reducer. I built 2 testing saga files and one root saga (I wanted to make rootSaga, like combineReducer), so this is my rootSaga :

import * as SpreadsheetSagas         from "../pages/spreadsheet/containers/spreadsheet/spreadsheet.saga";
import * as SpreadsheetFilterSagas   from "../pages/spreadsheet/containers/spreadsheet_filter/spreadsheet_filter.saga";

export default function* rootSaga() {
  yield all([
    ...Object.values(SpreadsheetSagas),
    ...Object.values(SpreadsheetFilterSagas)
  ].map(fork))
}

and this is one of my saga function:

export function* getData() {
   const response = yield call(ApiService.get);
   const payload = response ? response.data : {};
   //send returned object back to reducer as payload:
   yield put({ type: 'GET_MOCK_DATA', payload});
}

and my store folder looks like:

const middleWare = [];

// Setup Redux-Saga.
const sagaMiddleware = createSagaMiddleware();
middleWare.push(sagaMiddleware);

const store = createStore(rootReducer, {}, 
compose(applyMiddleware(...middleWare)));

// Initiate the root saga.
sagaMiddleware.run(rootSaga);

So, when I run my app, it calls every saga functions - and this is correct way to implement sagas :? or I should have several rootSaga files which will be depend on current page, and then when I open page, run appropriate rootSaga? I hope I explained everything correctly :/ please give me any suggestions. thank you.

Upvotes: 3

Views: 1932

Answers (1)

Jed Richards
Jed Richards

Reputation: 12437

I think generally you just have one tree of sagas that relate to your entire app, not multiple root sagas for different pages/routes. You just attach the rootSaga once, as middleware.

So yes, when your app starts the entire tree of sagas starts and beings watching actions. Sagas interact globally with your store, so it makes sense for them to start globally with your app.

Only start the sagas that watch for actions (using take, takeEvery etc). Other sagas that make side effects, or call apis, shouldn't be invoked when your app starts.

Creating a tree of sagas similar to reducers and combineReducer is the right way to go too.

Upvotes: 2

Related Questions