Search code examples
reactjsreduxredux-saga

yield put trigger method in takeEvery, this can make endless loop


this is sagas.js file; when I run my web app, an endless loop appears, and log lots of 'getInitList' in console, why?

import {takeEvery, put} from 'redux-saga/effects';
import {INIT_LIST_DATA} from './actionTypes'
import "./actionTypes";
import axios from "axios";

function *getList() {
    console.log('getInitList')
    const res = yield axios.get('/todolist.json');
    const data = res.data
    yield put({
        type: INIT_LIST_DATA,
        value: data
    })
}

// generator 函数
function *mySaga() {
    console.log('mySaga')
    yield takeEvery(INIT_LIST_DATA, getList)
}

export default mySaga;

Solution

  • use different type for actions. you are listening for same types. in takeEvery when sagas sees INIT_LIST_DATA it runs *getList() and then inside you dispatch put with same action type INIT_LIST_DATA then your takeEvery will run again

    function *getList() {
        console.log('getInitList')
        // this logic should be inside try/catch block
        const res = yield axios.get('/todolist.json');
        const data = res.data
        yield put({
            // CHANGE type to INIT_LIST_DATA_SUCCESS
            type: INIT_LIST_DATA_SUCCESS,
            value: data
        })
    }
    
    function *mySaga() {
       console.log('mySaga')
       // CHANGE type to INIT_LIST_DATA_START
       yield takeEvery(INIT_LIST_DATA_START, getList)
      }