Created
August 11, 2019 17:06
-
-
Save agenthunt/b4fc571933eefe7b7c056a9e8264ad2c to your computer and use it in GitHub Desktop.
decoupled-routing-productsStateManager.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { all, call, fork, put, take } from "redux-saga/effects"; | |
export const types = { | |
GET_PRODUCTS_REQUEST: "@products/GET_PRODUCTS_REQUEST", | |
GET_PRODUCTS_PROGRESS: "@products/GET_PRODUCTS_PROGRESS", | |
GET_PRODUCTS_SUCCESS: "@products/GET_PRODUCTS_SUCCESS", | |
GET_PRODUCTS_FAILURE: "@products/GET_PRODUCTS_FAILURE", | |
}; | |
export const actions = { | |
getProducts(){ | |
return { | |
type: types.GET_PRODUCTS_REQUEST | |
} | |
} | |
} | |
const initialState = { | |
getProductsInProgress: false, | |
getProductsError: null, | |
products: {} | |
} | |
export function reducer(state = initialState, action){ | |
switch(action.type){ | |
case types.GET_PRODUCTS_PROGRESS: { | |
return { | |
...state, | |
getProductsInProgress: true, | |
getProductsError: null | |
} | |
}, | |
case types.GET_PRODUCTS_SUCCESS: { | |
return { | |
...state, | |
getProductsInProgress: false, | |
products: action.products | |
} | |
}, | |
case types.GET_PRODUCTS_FAILURE: { | |
return { | |
...state, | |
getProductsInProgress: false, | |
getProductsError: action.error | |
} | |
} | |
default: return state; | |
} | |
} | |
export function* rootSaga(args) { | |
const allSagas = Object.keys(watcherSagas).map(key => | |
fork(watcherSagas[key], args) | |
); | |
yield all([...allSagas]); | |
} | |
export const workerSagas = { | |
*getProductsSaga() { | |
try { | |
yield put({ | |
type: types.GET_PRODUCTS_PROGRESS | |
}); | |
const products = yield call(() => apiClient.getProducts()); | |
yield put.resolve({ | |
type: types.GET_PRODUCTS_SUCCESS, | |
products | |
}); | |
} catch (error) { | |
console.log(error); | |
yield put({ | |
type: types.GET_PRODUCTS_FAILURE, | |
error | |
}); | |
} | |
} | |
}; | |
const watcherSagas = { | |
*watchGetProductsRequestSaga(args) { | |
while (true) { | |
yield take(types.GET_PRODUCTS_REQUEST); | |
yield call(workerSagas.getProductsSaga); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment