redux-actions#handleActions JavaScript Examples
The following examples show how to use
redux-actions#handleActions.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: common.js From doraemon with GNU General Public License v3.0 | 6 votes |
strategy = handleActions({
'request strategy'(state, action) {
return { ...state, loaded: false }
},
'receive strategy'(state, action) {
const { res } = action.payload
const obj = {}
res.forEach(item => obj[item.id] = item.description)
return { data: res, link: obj, loaded: true }
},
}, strategyState())
Example #2
Source File: index.js From stayaway-app with European Union Public License 1.2 | 6 votes |
reducer = handleActions(
{
[types.SET_APP_LAUNCHED]: (state, { payload: launched }) =>
Object.freeze({
...state,
launched,
}),
[types.SET_UNSUPPORTED]: (state, { payload: unsupported }) =>
Object.freeze({
...state,
unsupported,
}),
},
initialState,
)
Example #3
Source File: index.js From stayaway-app with European Union Public License 1.2 | 6 votes |
reducer = handleActions(
{
[types.PERMISSION_GRANTED]: (state, { payload: name}) =>
Object.freeze({
...state,
[name]: true,
}),
[types.PERMISSION_DENIED]: (state, { payload: name}) =>
Object.freeze({
...state,
[name]: false,
}),
},
initialState,
)
Example #4
Source File: index.js From stayaway-app with European Union Public License 1.2 | 6 votes |
reducer = handleActions(
{
[types.SET_ONBOARDING]: (state, { payload: onboarding }) =>
Object.freeze({
...state,
onboarding,
}),
},
initialState,
)
Example #5
Source File: reducers.js From one-wallet with Apache License 2.0 | 6 votes |
reducer = handleActions(
{
[cacheActions.updateCode]: (state, action) => ({
...state,
code: {
...state.code,
[action.payload.network]: action.payload.code,
},
}),
[cacheActions.clearCode]: (state, action) => ({
...state,
code: {},
version: {},
clientVersion: '',
needCodeUpdate: true,
}),
[cacheActions.updateVersion]: (state, action) => ({
...state,
version: {
...state.version,
[action.payload.network]: action.payload.version,
},
needCodeUpdate: (action.payload.version !== state.version[action.payload.network]) ||
action.payload.version?.endsWith('SNAPSHOT') ||
action.payload.version?.endsWith('.0')
}),
[cacheActions.updateClientVersion]: (state, action) => ({
...state,
clientVersion: action.payload,
}),
[cacheActions.updateGlobalStats]: (state, action) => ({
...state,
global: { ...state.global, stats: action.payload }
}),
},
{
...initialState
}
)
Example #6
Source File: reducers.js From one-wallet with Apache License 2.0 | 6 votes |
reducer = handleActions(
{
[balanceActions.fetchBalanceSuccess]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
balance: action.payload.balance,
}
}),
[balanceActions.fetchTokenBalanceSuccess]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
tokenBalances: {
...state[action.payload.address]?.tokenBalances,
[action.payload.key]: action.payload.balance
}
}
}),
[balanceActions.deleteBalance]: (state, action) => ({
...omit([action.payload], state)
}),
},
{
...initialState
}
)
Example #7
Source File: login.js From pineapple-reactNative with MIT License | 6 votes |
reducer = handleActions(
{
[setProfile]: (state, { payload }) => ({
...state,
user_id: payload.user_id,
username: payload.username,
email: payload.email,
firstName: payload.first_name,
lastName: payload.last_name,
addressOne: payload.addressOne,
addressTwo: payload.addressTwo,
cardNumber: payload.cardNumber,
}),
[setAuthentication]: (state, { payload }) => {
if (payload === true) {
return { ...state, isAuthenticated: true };
}
return { ...state, isAuthenticated: false };
},
},
defaultState
)
Example #8
Source File: api.js From pineapple-reactNative with MIT License | 6 votes |
reducer = handleActions(
{
[setProducts]: (state,) => {
const objects = fetch('https://pineapple-rest-api.herokuapp.com/products')
.then((response) => response.json())
.then(async (responseJson) => {
const { products } = await responseJson;
return products;
});
return {
...state,
products: objects,
};
},
},
defaultState
)
Example #9
Source File: tabList.js From doraemon with GNU General Public License v3.0 | 6 votes |
tabListResult = handleActions({
'request tab list'(state, action) {
return { ...state, loading: false }
},
'update tab list'(state, action) {
const data = action.payload
const findList = state.list.find(tab => tab.key === data.key)
const list = findList === undefined ? [...state.list, data] : state.list
sessionStorage.setItem('tabList', JSON.stringify({ list, activeKey: data.key, loading: false }))
return { list, activeKey: data.key, loading: false }
},
'update tab checked'(state, action) {
const { activeKey } = action.payload;
sessionStorage.setItem('tabList', JSON.stringify({ ...state, activeKey, loading: false }))
return { ...state, activeKey, loading: false }
},
'delete tab from list'(state, action) {
const { targetKey } = action.payload
const list = []
let delIndex = 0
let { activeKey } = state
state.list.map((tab, index) => {
tab.key === targetKey ? delIndex = index : list.push(tab)
})
if (state.activeKey === targetKey) {
// eslint-disable-next-line no-nested-ternary
activeKey = list[delIndex] ? list[delIndex].key :
(list[delIndex - 1] ? list[delIndex - 1].key : '')
}
sessionStorage.setItem('tabList', JSON.stringify({ list, activeKey, loading: false }))
return { list, activeKey, loading: false }
},
}, initialState)
Example #10
Source File: common.js From doraemon with GNU General Public License v3.0 | 6 votes |
allRetrievalResult = handleActions({
'request all retrieval'(state, action) {
return { ...state, loading: true }
},
'receive all retrieval'(state, action) {
// eslint-disable-next-line no-unused-vars
const { req, res } = action.payload
return { ...res.data, loading: false }
},
}, allRetrievalState)
Example #11
Source File: common.js From doraemon with GNU General Public License v3.0 | 6 votes |
gFormCache2 = handleActions({
'set gform cache2'(state, action) {
const { cacheKey, cacheContent } = action.payload
if (cacheKey === undefined) {
throw new Error('cacheKey不能是undefined')
}
if (cacheContent === undefined) {
throw new Error('cacheContent不能是undefined')
}
state[cacheKey] = { ...state[cacheKey], ...cacheContent }
return { ...state }
},
'clear gform cache2'(state, action) {
return cache2()
},
}, cache2())
Example #12
Source File: common.js From doraemon with GNU General Public License v3.0 | 6 votes |
loginData = handleActions({
'request login'(state, action) {
return { ...state, loaded: false }
},
'receive login'(state, action) {
// eslint-disable-next-line no-unused-vars
const { res } = action.payload
return { data: res, loaded: true }
},
// 没有返回或者错误
'reject login'(state, action) {
return { loaded: true }
},
}, loginState())
Example #13
Source File: common.js From doraemon with GNU General Public License v3.0 | 6 votes |
promethus = handleActions({
'request promethus'(state, action) {
return { ...state, loaded: false }
},
'receive promethus'(state, action) {
const { res } = action.payload
const obj = {}
console.log('set', res)
res.forEach(item => obj[item.id] = item.name)
return { data: res, link: obj, loaded: true }
},
}, promethusState())
Example #14
Source File: cheese.action.js From EMP with MIT License | 5 votes |
cheeseReducer = handleActions(
{ [cheeseConstants.CHEESELIST_SUCCEESS]: (state, action) => ({ cheeses: action.cheeses})
},
initialState
)
Example #15
Source File: review.action.js From EMP with MIT License | 5 votes |
reviewReducer = handleActions(
{ [reviewConstants.REVIEW_SUCCESS]: (state, action) => ({ reviews: action.reviews }),
},
initialState
)
Example #16
Source File: user.action.js From EMP with MIT License | 5 votes |
userReducer = handleActions(
{ [userConstants.LOGIN_SUCCESS]: (state, action) => ({ loggingIn: true, user: action.user }) },
initialState,
)
Example #17
Source File: lang.js From doraemon with GNU General Public License v3.0 | 5 votes |
langInfo = handleActions({
'change lang'(state, action) {
const { payload } = action
return { ...state, lang: payload }
},
}, { lang: '中文' })
Example #18
Source File: demo.js From doraemon with GNU General Public License v3.0 | 5 votes |
demoResult = handleActions({
'update demo'(state, action) {
console.log(state, action)
return { ...state, loading: true, test: true }
},
}, { init: 0 })
Example #19
Source File: index.js From mixbox with GNU General Public License v3.0 | 4 votes |
/**
* 获取并整合 actions reducers
* @param models
* @returns {{actions, reducers: {pageState}}}
*/
export function getActionsAndReducers({models}) {
const syncKeys = Object.keys(models).filter(key => {
const {syncStorage} = models[key];
return !!syncStorage;
});
const utils = actionUtils({syncKeys});
let _actions = checkAction({utils});
let _reducers = {};
Object.keys(models).forEach(modelName => {
const model = models[modelName];
let {
initialState = {},
syncStorage,
actions = {},
reducers = {},
} = model;
const __actionTypes = {};
initialState.__actionTypes = __actionTypes;
// 处理action reducer 合并写法
// 除去'initialState', 'syncStorage', 'actions', 'reducers'等约定属性,其他都视为actions与reducers合并写法
const ar = {};
Object.keys(model).forEach(item => {
if (['initialState', 'syncStorage', 'actions', 'reducers'].indexOf(item) === -1) {
ar[item] = model[item];
}
});
const arActions = {};
const arReducers = {};
Object.keys(ar).forEach((actionName, index) => {
const type = `type-${actionName}-${modelName}-${index}`.toUpperCase(); // 保证唯一并增强type可读性,方便调试;
__actionTypes[actionName] = type;
const arValue = ar[actionName];
if (typeof arValue === 'function') { // ar 函数写法
arActions[actionName] = createAction(type);
// arReducers[type] = arValue;
arReducers[type] = (state, action) => {
const {payload} = action;
return arValue(payload, state, action);
};
} else { // ar 对象写法
let {payload = identity, meta, reducer = (state) => ({...state})} = arValue;
// 处理meta默认值
if (!meta) {
if (payload && typeof payload.then === 'function') { // is promise
meta = commonAsyncMeta; // 异步默认meta
} else {
meta = identity; // 非异步默认 meta
}
}
let metaCreator = meta;
let payloadCreator = payload;
// 非函数时,处理
if (typeof payloadCreator !== 'function') payloadCreator = () => payload;
if (typeof metaCreator !== 'function') metaCreator = () => meta;
arActions[actionName] = createAction(type, payloadCreator, metaCreator);
arReducers[type] = reducer;
}
});
reducers = {...reducers, ...arReducers};
actions = {...actions, ...arActions};
// 处理reducer
const __reducers = {};
Object.keys(reducers).forEach(key => {
const reducer = reducers[key];
if (typeof reducer === 'object') {
// 对象写法 视为异步reducer
// _handleAsyncReducer内部对新、旧state自动进行了合并,异步reducer各个函数(padding、resolve等)只需要返回新数据即可
__reducers[key] = _handleAsyncReducer(reducer);
} else {
// 函数视为普通reducer, 进行新、旧state合并,model中的reducer只返回新数据即可
__reducers[key] = (state, action) => {
const newState = reducer(state, action) || {}; // 允许reducer不返回数据
// 检测 newState是否为对象
const isObject = typeof newState === 'object' && !Array.isArray(newState);
if (!isObject) {
console.error(`model method must return an object! check '${modelName}' method`);
}
// 检测新数据是否存在未在初始化state中定义的数据
const newStateKeys = Object.keys(newState);
const initialStateKeys = Object.keys(initialState);
newStateKeys.forEach(newKey => {
if (!initialStateKeys.includes(newKey)) {
console.error(`model method return {${newKey}} is not in ${modelName}.initialState! please define '${newKey}' in ${modelName}.initialState!`);
}
});
return {
...state,
...newState,
};
};
}
});
if (syncStorage) {
// 为meta添加__model_sync_name 和 __model_sync_state 属性,同步中间件会用到
Object.keys(actions).forEach(item => {
const actionCreator = actions[item];
actions[item] = (...args) => {
const action = actionCreator(...args);
action.meta = action.meta === void 0 ? {} : action.meta;
if (typeof action.meta !== 'object') throw new Error(`when model has syncStorage property,meta must be an object! check ${modelName} ${item} action method`);
action.meta.__model_sync_name = modelName;
action.meta.__model_sync_state = syncStorage;
return action;
};
});
// 从 store中恢复数据的reducer 如果为定义,使用默认reducers
if (!__reducers[actionTypes.GET_STATE_FROM_STORAGE]) {
__reducers[actionTypes.GET_STATE_FROM_STORAGE] = (state, action) => {
const {payload = {}} = action;
// state 为当前模块的初始化数据,data为当前模块存储的数据
const data = payload[modelName] || {};
// 深层结构的数据,会导致默认值失效,要使用递归,精确赋值
return setObjectByObject(state, data);
};
}
}
_actions[modelName] = actions;
_reducers[modelName] = handleActions(__reducers, initialState);
});
return {
actions: _actions,
reducers: _reducers,
};
}
Example #20
Source File: reducers.js From one-wallet with Apache License 2.0 | 4 votes |
reducer = handleActions(
{
[globalActions.migrate]: (state, action) => ({
...state,
network: state.network || action?.payload?.network || config.defaults.network,
relayer: state.relayer || action?.payload?.relayer || config.defaults.relayer,
relayerSecret: state.relayerSecret || action?.payload?.relayerSecret || config.defaults.relayerSecret,
}),
[globalActions.setDev]: (state, action) => ({
...state,
dev: action.payload
}),
[globalActions.setV2Ui]: (state, action) => ({
...state,
v2ui: action.payload
}),
[globalActions.setUiTheme]: (state, action) => ({
...state,
theme: action.payload
}),
[globalActions.setKnownAddress]: (state, action) => ({
...state,
knownAddresses: {
...state.knownAddresses,
[action.payload.address]: {
...state.knownAddresses?.[action.payload.address],
label: action.payload.label,
address: action.payload.address,
network: action.payload.network,
domainName: action.payload.domainName,
createTime: action.payload.creationTime,
lastUsedTime: action.payload.lastUsedTime,
numUsed: action.payload.numUsed,
domain: action.payload.domain
}
},
}),
[globalActions.deleteKnownAddress]: (state, action) => {
const { [action.payload]: deleted, ...restKnownAddresses } = state.knownAddresses
return {
...state,
knownAddresses: restKnownAddresses
}
},
// Status
[globalActions.setFetchStatus]: (state, action) => ({
...state,
fetching: action.payload,
}),
[globalActions.setError]: (state, action) => ({
...state,
error: action.payload,
}),
[globalActions.selectWallet]: (state, action) => ({
...state,
selectedWallet: action.payload,
}),
// Price
[globalActions.fetchPriceSuccess]: (state, action) => ({
...state,
price: action.payload,
}),
// Relayer
[globalActions.setRelayer]: (state, action) => ({
...state,
relayer: action.payload,
}),
[globalActions.setRelayerSecret]: (state, action) => ({
...state,
relayerSecret: action.payload,
}),
// Network
[globalActions.setNetwork]: (state, action) => ({
...state,
network: action.payload,
}),
},
{
...initialState
}
)
Example #21
Source File: reducers.js From one-wallet with Apache License 2.0 | 4 votes |
reducer = handleActions(
{
// Auto-migrate for old structure: `{wallets: {address: wallet}}`
[walletActions.autoMigrateWallets]: (state) => {
const currentEntries = Object.entries(state)
const oldWalletEntries = Object.entries(state.wallets || {})
const validEntries = oldWalletEntries.concat(currentEntries).filter(([_, wallet]) => wallet.root && wallet.address)
return Object.fromEntries(validEntries)
},
[walletActions.fetchWalletSuccess]: (state, action) => ({
...state,
[action.payload.address]: { ...state[action.payload.address], ...action.payload },
}),
[walletActions.updateWallet]: (state, action) => ({
...state,
[action.payload.address]: action.payload._merge ? omit(['_merge'], { ...state[action.payload.address], ...action.payload }) : action.payload
}),
[walletActions.deleteWallet]: (state, action) => ({
...omit([action.payload], state),
}),
[walletActions.trackTokens]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
trackedTokens: [...(state[action.payload.address]?.trackedTokens || []), ...action.payload.tokens],
untrackedTokens: (state[action.payload.address]?.untrackedTokens || []).filter(k => (action.payload.tokens || []).find(t => t.key === k) === undefined)
}
}),
[walletActions.untrackTokens]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
trackedTokens: (state[action.payload.address]?.trackedTokens || []).filter(e => action.payload.keys.find(k => k === e.key) === undefined),
untrackedTokens: uniq([...(state[action.payload.address]?.untrackedTokens || []), ...action.payload.keys])
}
}),
[walletActions.setSelectedToken]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
selectedToken: action.payload.token
}
}),
[walletActions.bindDomain]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
domain: action.payload.domain
}
}),
[walletActions.userAcknowledgedToSaveAddress]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
acknowledgedToSaveAddress: true
}
}),
[walletActions.userAcknowledgedNewRoot]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
acknowledgedNewRoot: action.payload.root
}
}),
[walletActions.userSkipVersion]: (state, action) => ({
...state,
[action.payload.address]: {
...state[action.payload.address],
skipVersion: action.payload.version
}
}),
},
{
...initialState
}
)
Example #22
Source File: index.js From stayaway-app with European Union Public License 1.2 | 4 votes |
reducer = handleActions(
{
[types.SET_SIGN_UP_DATE]: (state, { payload: signUpDate }) => {
Storage.setItem('signup_date', signUpDate);
return Object.freeze({
...state,
signUpDate,
});
},
[types.SET_TRACING_ENABLED]: (state, { payload: tracingEnabled }) => {
Storage.setItem('tracing_enabled', tracingEnabled.toString());
return Object.freeze({
...state,
tracingEnabled,
});
},
[types.SET_STATUS]: (state, { payload: status }) => {
Storage.setItem('status', JSON.stringify(status));
return Object.freeze({
...state,
status,
});
},
[types.SET_LANGUAGE]: (state, { payload: language }) => {
Storage.setItem('language', language.languageTag);
return Object.freeze({
...state,
language,
});
},
[types.SET_THEME]: (state, { payload: theme }) => {
Storage.setItem('theme', theme);
return Object.freeze({
...state,
theme,
});
},
[types.SUBMIT_DIAGNOSIS_PENDING]: (state) => (
Object.freeze({
...state,
submittingDiagnosis: {
loading: true,
error: '',
},
})
),
[types.SUBMIT_DIAGNOSIS_ERROR]: (state, { payload: error }) => (
Object.freeze({
...state,
submittingDiagnosis: {
loading: false,
error,
},
})
),
[types.SUBMIT_DIAGNOSIS_DONE]: (state) => (
Object.freeze({
...state,
submittingDiagnosis: {
loading: false,
error: '',
},
})
),
[types.SETUP_NEW_ACCOUNT_PENDING]: (state) => (
Object.freeze({
...state,
settingUpNewAccount: {
loading: true,
},
})
),
[types.SETUP_NEW_ACCOUNT_DONE]: (state) => (
Object.freeze({
...state,
settingUpNewAccount: {
loading: false,
},
})
),
},
initialState,
)
Example #23
Source File: index.js From stayaway-app with European Union Public License 1.2 | 4 votes |
reducer = handleActions(
{
[types.OPEN_NETWORK_MODAL]: (state) =>
Object.freeze({
...state,
network: true,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.CLOSE_NETWORK_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.OPEN_SERVER_ERROR_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: true,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.CLOSE_SERVER_ERROR_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.OPEN_TOO_MUCH_REQUESTS_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: true,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.CLOSE_TOO_MUCH_REQUESTS_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.OPEN_INVALID_CODE_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: true,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.CLOSE_INVALID_CODE_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.OPEN_EXPIRED_CODE_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: true,
loading: false,
protector: false,
contact: false,
}),
[types.CLOSE_EXPIRED_CODE_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.OPEN_LOADING_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: true,
protector: false,
contact: false,
}),
[types.CLOSE_LOADING_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
[types.OPEN_PROTECTOR_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: true,
}),
[types.CLOSE_PROTECTOR_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
}),
[types.OPEN_CONTACT_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: true,
}),
[types.CLOSE_CONTACT_MODAL]: (state) =>
Object.freeze({
...state,
network: false,
server_error: false,
too_much_requests: false,
invalid_code: false,
expired_code: false,
loading: false,
protector: false,
contact: false,
}),
},
initialState,
)