📜  api.fetch saga - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:41.048000             🧑  作者: Mango

代码示例1
import { takeLatest, call, put } from 'redux-saga/effects';

// watcher saga: watches for actions dispatched to the store, starts worker saga
export function* watcherSaga() {
    yield takeLatest('FETCH_CUSTOMERS', workerSaga);
}

// worker saga: makes the api call when watcher saga sees the action
function* workerSaga() {
    try {
        const response = yield call(fetch, 'https://mydomain/api/customers');
        const customers = response.data.customers;

        // dispatch a success action to the store with the customers
        yield put({ type: 'CUSTOMERS_FETCHED', customers });
    } catch (error) {
        // dispatch a failure action to the store with the error
        yield put({ type: 'CUSTOMERS_FETCH_ERROR', error });
    }
}