godsenal
godsenal

Reputation: 387

do some works after asynchronous function in redux saga

I'm working on project with redux-saga. I was using thunk before so i could do some works after api request like,

componentDidMount(){
  login().then((success)=>{
    redirectToProfilePage();
  })
}

because action in redux-thunk returns promise. but when i'm trying to do this in redux-saga, i can't use then since saga doesn't return promise.

So i'm using componentWillReceiveProps to solve this, but i think it's not a appropriate solution.

Should i do this work in saga generator? Or is there any other better way?

Upvotes: 0

Views: 442

Answers (1)

nicktu12
nicktu12

Reputation: 129

In order to use the full potential of Sagas, you will want to dispatch an action in componentDidMount.

In your sagas.js file for that component, create a function generator to listen for the action in componentDidMount:

function* listenForLoginAction(){
    yield takeLatest('LOGIN_ACTION', loginSaga)
}

Then your loginSaga will handle the async stuff in the order you tell it to. Your loginSaga could look something like this:

function* loginSaga(action){
    try{
        const loginResponse = yield call(loginFunc, varsForloginFunc)
        yield put({type: 'LOGIN_SUCCESS', loginResponse})
    } catch (error) {
        yield put({type: 'LOGIN_FAIL', message: error.message})
    }
}

Using yield call and yield put, in conjuction with listening for a specific action using takeLatest or takeEvery, allows you to write code that will wait to execute until the line above it has completed.

Hope that helps!!

Upvotes: 2

Related Questions