Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

api.fetch saga

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 });
    }
}
 
PREVIOUS NEXT
Tagged: #saga
ADD COMMENT
Topic
Name
2+5 =