Last active
January 9, 2019 00:24
-
-
Save imranariffin/85aa8698a0915b2f3a1b0296dbb0e4b8 to your computer and use it in GitHub Desktop.
Redux middlewares: logger, api & persistence-storage
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
export default (client) => ({ dispatch }) => (next) => async (action) => { | |
if (!action.types || | |
action.types.length !== 3 || | |
!action.method || | |
!action.data | |
) { | |
return next(action) | |
} | |
const { | |
types: [ | |
pending, | |
success, | |
failure | |
], | |
method, | |
data | |
} = action | |
dispatch({ | |
type: pending, | |
data | |
}) | |
try { | |
const { data: responseData } = await apiClient.call(method, data) | |
dispatch({ | |
type: success, | |
responseData | |
}) | |
} catch (error) { | |
dispatch({ | |
type: failure, | |
error | |
}) | |
} | |
return next(action) | |
} |
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
export default (logger) => ({ getState }) => (next) => (action) => { | |
logger.log('prev state', getState()) | |
logger.log('action', action) | |
const returnedValue = next(action) | |
logger.log('next state', getState()) | |
return returnedValue | |
} |
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
export default (storage) => ({ getState }) => (next) => async (action) => { | |
try { | |
await storage.setItem('state', getState()) | |
} catch (_) {} | |
return next(action) | |
} |
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 { createStore, applyMiddleware } from 'redux' | |
import storage from '@storage' | |
import apiClient from '@apiClient' | |
import logger from '@logger' | |
import reducer from '@reducers' | |
import apiMiddleware from './apiMiddleware' | |
import storageMiddleware from './storageMiddleware' | |
import loggerMiddleware from './loggerMiddleware' | |
const store = createStore( | |
reducer, | |
applyMiddleware( | |
loggerMiddleware(logger), | |
apiMiddleware(apiClient), | |
storageMiddleware(storage) | |
) | |
) | |
export default store |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment