slopeofhope
slopeofhope

Reputation: 776

Calling yield in callback, redux saga gives me an exception why?

so I commented out where it gives me a traceback.

export function* watchFileReader(){
const action = yield take("DROP_FILE")
console.log('action', action)
let file = action.file[0];
readFile(file, function(e){
  sessionStorage.removeItem('img')
  console.log('alskdjfalsdjkf', e.target.result)
  sessionStorage.setItem('img', e.target.result)
  // yield put({type: "UDATE", {img: e.target.result})
   })
}

update: this is my promisified function to get the code to work.

 function readFileWithPromise(file){
  return new Promise((resolve, reject) => {
   readFile(file, function(e){
     if (e){
      resolve(e)
     }else{
      reject(e)
     }
   })
 })
}

Upvotes: 4

Views: 1840

Answers (1)

Kokovin Vladislav
Kokovin Vladislav

Reputation: 10421

you can't use yield in callback , there are two ways to avoid this:

  1. cps effect . DOCS LINK

    import { cps , ...  } from 'redux-saga/effects';
    
    export function* watchFileReader(){
      const action = yield take("DROP_FILE")
      let file = action.file[0];
    
      let e = yield cps(readFile,file); <----------------
    
      sessionStorage.removeItem('img')
      sessionStorage.setItem('img', e.target.result)
      yield put({type: "UPDATE", img: e.target.result})
    }
    

    note : function must call cb(null, result) to notify the middleware of a successful result. If fn encounters some error, then it must call cb(error) in order to notify the middleware that an error has occurred.


  2. promisify your function

    function readFileWithPromise(file){
         return new Promise((resolve,reject)=>{
             readFile(file,(err, res) => err ? reject(err) : resolve(res));
        });
    }
    

    and then call it

    import { call, ...  } from 'redux-saga/effects';
    
    export function* watchFileReader(){
      const action = yield take("DROP_FILE")
      let file = action.file[0];
    
      let e = yield call(readFileWithPromise,file); <----------------
    
      sessionStorage.removeItem('img')
      sessionStorage.setItem('img', e.target.result)
      yield put({type: "UPDATE", img: e.target.result})
    }
    

LIVE DEMO for two examples

Upvotes: 5

Related Questions