Skip to content

Instantly share code, notes, and snippets.

@wufe
Last active November 17, 2016 13:30
Show Gist options
  • Save wufe/a1cd35d2c8fd9997d4ec69895eea696a to your computer and use it in GitHub Desktop.
Save wufe/a1cd35d2c8fd9997d4ec69895eea696a to your computer and use it in GitHub Desktop.
redux-saga summary

Redux-Saga - Summary

The middleware

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> )

The rootSaga generator

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 ).

watchFetchLinks is a single saga, it watches for actions

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.

The real function that fetches links: fetchLinks (ofc)

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.

The actions: same as usual

/* ACTIONS */

let requestLinksSucceeded: any = ( links ) => {
	return {
		type: REQUEST_LINKS_SUCCEEDED,
		links
	};
};

let requestLinksFailed: any = ( message ) => {
	return {
		type: REQUEST_LINKS_FAILED,
		message,
		error: true
	}	
};

The reducer

/* 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment