Skip to content

Instantly share code, notes, and snippets.

@imranariffin
Last active January 9, 2019 00:24
Show Gist options
  • Save imranariffin/85aa8698a0915b2f3a1b0296dbb0e4b8 to your computer and use it in GitHub Desktop.
Save imranariffin/85aa8698a0915b2f3a1b0296dbb0e4b8 to your computer and use it in GitHub Desktop.
Redux middlewares: logger, api & persistence-storage
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)
}
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
}
export default (storage) => ({ getState }) => (next) => async (action) => {
try {
await storage.setItem('state', getState())
} catch (_) {}
return next(action)
}
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