Beginner Guide for Redux-Saga


Redux-Saga is a redux middleware which aims to make application side effects(i.e. Asynchronous data fetching and accessing the browser cache) easier to manage, more effective to execute, and better handling failures.

In this article, I would like to share Redux-Saga information for beginners.

๐ŸšŒ Installation

yarn add redux-saga

๐Ÿฏ Beginner Tutorial

We are going to use the trivial counter demo from the Redux tutorial repository.

The application is quite simple but is a good fit to illustrate the basic concepts of redux-saga.

Initial Setup

In the command line, run:

# clone tutorial repository
git clone https://github.com/redux-saga/redux-saga-beginner-tutorial.git
cd redux-saga-beginner-tutorial

# install npm libraries
yarn

# start application
yarn start

๐ŸŽ‚ Hello Sagas!

There are two buttons: Increment and Decrement a counter. From now on, we will add Async Increment button to increament the counter 1 seconde after your click and a callback onIncrementAsync.

Create a file sagas.js then add the folling snippet:

import { delay } from 'redux-saga';
import { put, takeEvery, all } from 'redux-saga/effects'

export function* helloSaga() {
console.log('Hello Sagas!');
}

// Our Worker Saga: will perform the ansync increment task
export function* incrementAsync() {
yield delay(1000); // sleeps for 1 second, yield will suspend the Saga until the Promise completes
yield put({ type: 'INCREMENT' });
}

// Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC
function* watchIncrementAsync() {
yield takeEvery('INCREMENT_ASYNC', incrementAsync);
}

// notice how we now only export the rootSaga
// single entry point to start all Sagas at once
export default function* rootSaga() {
yield all([
helloSaga(),
watchIncrementAsync(),
])
}

We will make the changes to main.js:

import "babel-polyfill"

import React from 'react'
import ReactDOM from 'react-dom'
import {createStore, applyMiddleware} from 'redux'
import createSagaMiddleware from 'redux-saga';

import Counter from './Counter'
import reducer from './reducers'
import rootSaga from './sagas';

// Connect Saga middleware to the Redux store
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware),
);
sagaMiddleware.run(rootSaga);

const action = type => store.dispatch({type});

function render() {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => action('INCREMENT')}
onDecrement={() => action('DECREMENT')}
onIncrementAsync={() => action('INCREMENT_ASYNC')} />,
document.getElementById('root')
)
}

render();
store.subscribe(render);

Weโ€™ll provide an additional button and a callback onIcrementAsync to Counter.js:

import React, { Component, PropTypes } from 'react'

const Counter = ({ value, onIncrement, onDecrement, onIncrementAsync }) => {
return <div>
<button onClick={onIncrementAsync}>
Increment after 1 second
</button>
{' '}
<button onClick={onIncrement}>
Increment
</button>
{' '}
<button onClick={onDecrement}>
Decrement
</button>
<hr />
<div>
Clicked: {value} times
</div>
</div>;
};

Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired,
onIncrementAsync: PropTypes.func.isRequired,
};

export default Counter

๐ŸŽณ More Detail

If you want to know more detail information, please see official document Beginner Tutorial ยท Redux-Saga.

In the document, It are described for concept, how to write Unit Test for redux-saga or some other kindness information to use.

๐Ÿ–ฅ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!