Monday, May 20, 2024
119
rated 0 times [  125] [ 6]  / answers: 1 / hits: 16849  / 7 Years ago, sun, march 26, 2017, 12:00:00

Because yield-statement isn't allowed within a callback, how can i use the put feature of redux-saga within a callback?



I'd like to have the following callback:



function onDownloadFileProgress(progress) {
yield put({type: ACTIONS.S_PROGRESS, progress})
}


This isn't working and ends up in unexpected token, because yield is not allowed in a plain function. Otherwise i can't pass a callback as a function *, that would allow yield. ES6 seems broken here.



I've read that redux-saga provides some features called channels, but to be honest, i didn't get it. I've read several times about these channels and example code, but in all examples they've solved very difficult and different problems, not my simple case and at the end of the day i've got up there.



Can someone tell me a solution how to deal with this issue?



The whole context:



function onDownloadFileProgress(progress) {
yield put({type: ACTIONS.S_PROGRESS, progress})
}

export function * loadFile(id) {
let url = `media/files/${id}`;

const tempFilename = RNFS.CachesDirectoryPath + '/' + id;

const download = RNFS.downloadFile( {
fromUrl: url,
toFile: tempFilename,
background: false,
progressDivider: 10,
progress: onDownloadFileProgress,
})

yield download.promise;

}

More From » ecmascript-6

 Answers
151

One possible solution, as you already mentioned, is to use channels. Here is an example that should work in your case:



import { channel } from 'redux-saga'
import { put, take } from 'redux-saga/effects'

const downloadFileChannel = channel()

export function* loadFile(id) {
...
const download = RNFS.downloadFile({
...
// push `S_PROGRESS` action into channel on each progress event
progress: (progress) => downloadFileChannel.put({
type: ACTIONS.S_PROGRESS,
progress,
}),
})
...
}

export function* watchDownloadFileChannel() {
while (true) {
const action = yield take(downloadFileChannel)
yield put(action)
}
}


The idea here is that we will push a S_PROGRESS action on the channel for each progress event that is emitted from RNFS.downloadFile.



We also have to start another saga function that is listening to each pushed action in a while loop (watchDownloadFileChannel). Everytime an action has been taken from the channel, we use the normal yield put to tell redux-saga that this action should be dispatched.



I hope this answer will help you.


[#58379] Friday, March 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;