import {default as Saga} from 'redux-saga'; // or import Saga
import {createStore} from 'redux';
const saga = Saga();
const store = createStore(
<rootReducer>,
<initialState>
applyMiddleware( saga )
);
saga.run( <rootSaga> )
let rootSaga: any = function*( getState ){
yield fork( watchFetchLinks, getState )
}
Just give it to Saga. It will simply call (non-blocking) all the processes defined ( in this case, watchFetchLinks
only ).
let watchFetchLinks: any = function*( getState ){
yield* takeLatest(FETCH_LINKS, fetchlinks);
}
In this case watchFetchLinks
watches for FETCH_LINKS
action, to be dispatched.
When it happens, calls fetchLinks
.
If the execution of fetchLinks
is not finished and another FETCH_LINKS
is thrown, the first fetchLinks
operation gets
terminated.
It is like an override of the execution.
let fetchLinks: any = function*( action ){
const {id} = action;
try{
const links = yield call( API.getLinksFromId( id ) )
yield put( requestLinksSucceeded( links ) )
}catch( error ){
yield put ( requestLinksFailed( error.message ) )
}
}
When fetchLinks
gets called is supposed to have a action (a payload).
The function uses the action to call the API and get links from server.
The yield
before call( API.getLinks...
is used to act synchronously while achieving asynchronicity.
If something wrong happens, the catch catches the error and calls the requestLinksFailed
which will throw a REQUEST_LINKS_FAILED
action, as described below.
If the request is successfull we all are happy the requestLinksSucceeded
function gets called instead.
/* ACTIONS */
let requestLinksSucceeded: any = ( links ) => {
return {
type: REQUEST_LINKS_SUCCEEDED,
links
};
};
let requestLinksFailed: any = ( message ) => {
return {
type: REQUEST_LINKS_FAILED,
message,
error: true
}
};
/* REDUCER */
let linksReducer: any = ( state = initialState, action ){
switch( action.type ){
case REQUEST_LINKS_SUCCEEDED:
return Object.assign({}, state, {
links: action.links
});
case REQUEST_LINKS_FAILED:
return Object.assign({}, state, {
links: []
});
default:
return state;
}
};
Acts as usual, putting the links in the global store.