Search code examples
reactjsreduxredux-sagayield

Can't use fetch inside yield call in redux saga


I am making an api call and based on the response, I have to update the state. This is what I am doing.

function* testEndpointConnectivity(action){
    const { testConnectivityUri, rowItem } = action.payload
    const res=  yield call( fetch(testConnectivityUri).then(response => {
        //something here
        })
    )
   
   yield put({type: SOME_ACTION});
   
}

But this doesn't work. I get the error

 Error: call: argument fn is undefined

At first I tried putting the yield put in the catch and then of the response, but stackoverflow told me to use yield call.

Please help here.


Solution

  • It's not correct

    if you check doc you will see the first argument it's function and then you can send arguments:

    call(fn, ...args)

    So, in your example correct variant must look like:

    function* testEndpointConnectivity(action) {
        const { testConnectivityUri, rowItem } = action.payload;
        const response = yield call(fetch, testConnectivityUri);
        // and in generator you can wait your answer, you dont need use .then
        console.log("response", response);
    
        yield put({ type: SOME_ACTION });
    
    }
    
     // this error mean, first argument in call function must be fetch
     Error: call: argument fn is undefined