Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux-saga: How to create multiple calls/side-effects programmatically for yield?

With redux-saga, one can execute multiple effects in parallel:

import { call } from 'redux-saga/effects'

// correct, effects will get executed in parallel
const [users, repos]  = yield [
  call(fetch, '/users'),
  call(fetch, '/repos')
]

How can i create those "call"-calls programmatically?

What i want to achieve is this:

Lets say i have an array with different parameters and i want to execute a request to a server per parameter, but in parallel with redux-saga:

const parameters = ['abc', 'def', 'ghi']

const allMyFetchCalls  = parameters.map( (p) => makeCallRequestWithParameter(p) );

makeCallRequestWithParameter would create a function call (or in redux-saga-speech: an effect) call(fetch, param) like in yield call(fetch, param)

const resultArray = yield allMyFetchCalls;

Is this possible and if so, how?

like image 460
itinance Avatar asked Oct 14 '16 12:10

itinance


People also ask

How do you use yield call in Redux saga?

if you call yield put({ type: REFRESH_REQUEST}) your saga yields until the action is dispatched, but not until all effects were executed. Calling the generator directly will wait until the generator finished. Note that you should throw an error when calling refresh() directly when refreshing the token fails.

Which Redux saga function is used to create dispatch side effects?

put is another effect provided by redux-saga which can be used to dispatch actions in a saga.

What is takeEvery and takeLatest in Redux saga?

takeEvery - enables the use of several fetchData objects at the same time. At a given moment, we can start a new fetchData task while there are still one or more previous fetchData tasks which have not yet terminated. takeLatest - Only one fetchData task can be active at any given moment.

Is Redux saga multi thread?

The tasks are running on single CPU thread. This is cooperative multi-tasking — meaning that the individual task can handle over the execution by using the “yield” keyword (however, this depends on the task runner/scheduler implementation)


1 Answers

Please note that call effect doesn't call anything at the time. It just creates Plain JavaScript Object and returns. So what you want is not so difficult.

import { call } from 'redux-saga/effects'

const params = ['abc', 'def', 'ghi']
const responses  = yield params.map(p => call(fetch, p))
like image 134
kuy Avatar answered Sep 16 '22 13:09

kuy