Redux sagas
Where to Ajax ?
Redux Sagas
- In a Redux applications, where should we place the Ajax code ?
Where to Ajax ?
Redux Sagas
Component
Reducer
Action, State
State
UX
Props
Redux dispatcher
Redux Connect
Pure
In reducer
or in component ?
Where to Ajax ?
Redux Sagas
- Reducer
- No - it is supposed to be pure
- Component
- Maybe
- What if data is needed in other components
- Component becomes complex
Redux-saga
Reducer
Action, State
Redux-saga
- Watch the dispatched actions
- Perform the async/impure actions
- Dispatch another action
Redux dispatcher
Add a Redux saga
Redux-saga
The flow with saga
- User clicks on Load data button
- Component dispatches LOAD_DATA action
- Saga, watching for LOAD_DATA action, captures it,
- Saga triggers the loading code (fetch etc)
- Saga dispatches the DATA_LOADED action, after loading finishes
- Reducer processes it, updates the state
- Redux updates the props, component re-renders
Redux-saga
Reducer
Action, State
Redux-saga
Redux dispatcher
The flow
Component
State
UX
Props
Redux Connect
Redux-saga
The code
function* mySaga () {
yield take(LOAD_DATA)
result = yield call(fetch_etc)
yield put(DATA_LOADED, result)
}
Introduction
Redux-saga
redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, simple to test, and better at handling failures
(from the documentation)
Side effects
Redux-saga
"asynchronous things like data fetching and impure things like accessing the browser cache"
=>
- asynchronous
- impure
Pure and impure
Redux-saga
- Are concepts from functional programming
- Pure - has no side effects
- No state should change, no data should be assigned, nothing in the environment should change
- No database changes. No changes to global data.
- No IO
Pure and impure - No I/O
Redux-saga
// Writing to console
function foo() {
console.log('Hello World');
}
// Ajax calls
function bar() {
fetch('some-url').then('display it');
}
Redux and pure functions
Redux-saga
- Redux reducers must be pure
- Then how do we make Ajax calls ?
Pure and impure - changing globals
Redux-saga
// location
function foo() {
location.href = 'http://google.com';
}
// localStorage
function bar() {
localStorage.set('x', 1)
}
Redux sagas
By Abhishek Yadav
Redux sagas
- 810