Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Lidando com Efeitos Colaterais com Redux Saga
Search
Filipe Costa
May 13, 2017
Programming
230
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Lidando com Efeitos Colaterais com Redux Saga
Filipe Costa
May 13, 2017
More Decks by Filipe Costa
See All by Filipe Costa
Pitch - Lidando com Efeitos Colaterais com Redux Saga
filipebarcos
0
400
Rust for Rubysts
filipebarcos
2
260
Limpando Seu Código JS Com O Padrão Pub/Sub
filipebarcos
0
200
Tu trabalha em casa?? Que moleza hein!
filipebarcos
0
130
Rediscovering OOP in Rails World
filipebarcos
0
100
jQuery Bad Practices
filipebarcos
2
270
Intro to Ruby
filipebarcos
1
140
Other Decks in Programming
See All in Programming
「寝てても仕事が進む」Claude Codeで組む第二の脳
tomoyafujita2016
0
350
typoなんかねぇよ
raspython3
0
510
書籍「プロフェッショナルAI駆動開発」紹介スライド
juntaromatsumoto
0
450
Press start. Python's next generation.
willingc
PRO
3
110
AIの中の人になってみる
htkym
0
110
言葉の格闘技のススメ~紙とペンと言葉から始める、キャリアの描き方~
progresscicada
2
170
【デモ】Kiroで体験する仕様駆動開発|設計からコーディングまでAIと進める開発フロー
cmkudo
0
360
in-process GraphQL のすすめ #ginzajs
izumin5210
4
1.5k
思考垂れ流し開発 ~音声入力 × AIエージェント × 開発ハーネスによる試行錯誤~
npostring
0
130
AI Readyの正体はデータマネジメントだ メダリオン2.0の最前線
freee
PRO
0
370
進化を続けるGo toolsの現在地 / The Current State of Ever-Evolving Go Tools
hond0413
0
250
jsmini JavaScript Engine を作ってみた話
yosuke_furukawa
PRO
0
350
Featured
See All Featured
Six Lessons from altMBA
skipperchong
29
4.5k
Everyday Curiosity
cassininazir
0
290
Utilizing Notion as your number one productivity tool
mfonobong
4
550
Google's AI Overviews - The New Search
badams
0
1.1k
Navigating the moral maze — ethical principles for Al-driven product design
skipperchong
2
500
Speed Design
sergeychernyshev
33
2k
For a Future-Friendly Web
brad_frost
183
10k
Measuring Dark Social's Impact On Conversion and Attribution
stephenakadiri
2
260
End of SEO as We Know It (SMX Advanced Version)
ipullrank
3
4.4k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
37
6.6k
Balancing Empowerment & Direction
lara
6
1.2k
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
580
Transcript
Lidando com Efeitos Colaterais com Redux Saga @filipebarcos
Redux
"Evolui ideias do Flux, mas evita suas complexidades pegando dicas
do Elm" — github.com/reactjs/redux Redux
Redux UI Reducer Store Action dispatched (currentState, action) => newState
New State
Pausa Dramática
O que é uma Função Pura?
"É uma função em que seus parâmetros são a única
coisa que influenciam no seu valor de retorno"
"É uma função em que seus parâmetros são a única
coisa que influenciam no seu valor de retorno" — eu
Redux UI Reducer Store Action dispatched (currentState, action) => newState
New State
Redux UI Middleware Reducer Store Action dispatched (currentState, action) =>
newState New State Action forwarded Action dispatched
Redux Saga
github.com/redux-saga/redux-saga
E o que é uma “Saga”?
None
“…a sequence of transactions that can be interleaved with other
transactions.” http://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf — Hector Garcia-Molina e Kenneth Salem
“…a sequence of transactions that can be interleaved with other
transactions.” http://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf — Hector Garcia-Molina e Kenneth Salem
“…a saga is like a separate thread in your application
that's solely responsible for side effects.” — https://github.com/redux-saga/redux-saga
Como eu é possível parar uma execução de uma função
em JS?
JS Generator Functions*
ES6 Feature
https://davidwalsh.name/es6-generators http://2ality.com/2015/03/es6-generators.html
https://davidwalsh.name/es6-generators function* foo(x) { const y = 2 * (yield
(x + 1)); const z = yield (y / 3); return (x + y + z); } const it = foo(5); // note: not sending anything into `next()` here console.log(it.next()); // { value:6, done:false } console.log(it.next(12)); // { value:8, done:false } console.log(it.next(13)); // { value:42, done:true }
Alguns exemplos
https://redux-saga.github.io/redux-saga/docs/basics/UsingSagaHelpers.html import { call, put } from 'redux-saga/effects'; export function*
fetchData(action) { try { const data = yield call(Api.fetchUser, action.payload.url); yield put({type: 'FETCH_SUCCEEDED', data}); } catch (error) { yield put({type: 'FETCH_FAILED', error}); } } function* watchFetchData() { yield takeEvery('FETCH_REQUESTED', fetchData); }
https://redux-saga.github.io/redux-saga/docs/basics/UsingSagaHelpers.html import { takeEvery } from 'redux-saga'; // FETCH_USERS function*
fetchUsers(action) { ... } // CREATE_USER function* createUser(action) { ... } // use them in parallel export default function* rootSaga() { yield takeEvery('FETCH_USERS', fetchUsers); yield takeEvery('CREATE_USER', createUser); }
E os testes?
import { call, put } from 'redux-saga/effects'; export function* fetchData(action)
{ try { const data = yield call(Api.fetchUser, action.payload.url); yield put({type: 'FETCH_SUCCEEDED', data}); } catch (error) { yield put({type: 'FETCH_FAILED', error}); } } function* watchFetchData() { yield takeEvery('FETCH_REQUESTED', fetchData); } https://redux-saga.github.io/redux-saga/docs/basics/UsingSagaHelpers.html
import { call, put } from 'redux-saga/effects'; export function* fetchData(action)
{ try { const data = yield call(Api.fetchUser, action.payload.url); yield put({type: 'FETCH_SUCCEEDED', data}); } catch (error) { yield put({type: 'FETCH_FAILED', error}); } } function* watchFetchData() { yield takeEvery('FETCH_REQUESTED', fetchData); } https://redux-saga.github.io/redux-saga/docs/basics/UsingSagaHelpers.html
{ CALL: { fn: Api.fetchUser, args: [“/users”], }, }
const generator = fetchData(); expect(generator.next()).toEqual({ done: false, value: call(Api.fetchUser, action.payload.url)
});
Tá, mas e aí?
redux-saga === redux-thunk + testabilidade
None
None
Ações Futuras
take x takeEvery
function* watchThis() { yield takeEvery('THIS', doThat); }
function* watchThis() { while(true) { yield take('THIS', doThat); } }
function* watchDeaths() { yield take('DIE', newTry); yield take('DIE', newTry); yield
take('DIE', put, { type: 'GAME_OVER' }); }
Chamadas “não-bloqueantes”
fork
function* mySaga() { while(true) { yield take(''); yield call(foo); yield
call(bar); } }
function* mySaga() { while(true) { yield take(''); yield fork(foo); yield
fork(bar); } }
Executar tarefas em paralelo
const [visits, registrations] = yield all([ call(fetch, '/visits'), call(fetch, '/registrations')
]);
Corrida entre efeitos colaterais
const { posts, timeout } = yield race({ posts: call(fetch,
'/posts'), timeout: call(delay, 1000) });
Composição de Sagas
yield*
function* foo() { ... } function* bar() { ... }
function* baz() { ... } function* fooBarBaz() { yield* foo(); yield* bar(); yield* baz(); }
tests?
tests?
function* foo() { ... } function* bar() { ... }
function* baz() { ... } function* fooBarBaz() { yield call(foo); yield fork(bar); yield call(baz); }
Cancelamento de Tarefas
function* mySync() { try { while(true) { yield put({type: 'SYNC_STARTED'});
const result = yield call(syncMyFiles); yield call(delay, 500); } } finally { if (yield cancelled()) yield put({ type: 'SYNC_STOPED'}); } } function* myDropbox() { while(yield take('START_FILE_SYNC')) { const mySyncTask = yield fork(mySync); yield take('STOP_FILE_SYNC'); // this will cause the forked task to jump into its finally block yield cancel(mySyncTask); } }
gist.github.com/filipebarcos/ 0a137d6ca837c117f999958a365fc5b6
Obrigado. @filipebarcos