Created
May 12, 2019 13:37
-
-
Save sharvit/e160beddfa3b49f7bb306f0b2beeb44f to your computer and use it in GitHub Desktop.
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 React from 'react'; | |
import { connect } from 'react-redux'; | |
const AUDITS_API = 'AUDITS_API'; | |
const createConstTypes = (constName) => { | |
return { | |
REQUEST: `${constName}_REQUEST`, | |
REQUEST: `${constName}_SUCCESS`, | |
REQUEST: `${constName}_FAILURE`, | |
}; | |
}; | |
const fetchAudits = () => ({ | |
type: 'API', | |
action: 'GET', | |
url: 'some-url', | |
constName: AUDITS_API, | |
normalizeData: (response) => response.data, | |
}); | |
const createApiReducer = (constName) => { | |
const initialState = { data: null, isLoading: true }; | |
const actionTypes = createConstTypes(constName); | |
return (state = initialState, action) => { | |
switch (action.type) { | |
case actionTypes.REQUEST: | |
return state.set('data', action.payload.data); | |
case actionTypes.SUCCESS: | |
return state.set('data', action.payload.data); | |
case actionTypes.ERROR: | |
return state.set('data', action.payload.data); | |
default: | |
} | |
}; | |
}; | |
const createPage = ({ | |
name, | |
title, | |
Page, | |
ErrorPage, | |
EmptyPage, | |
LoadingPage, | |
onInit, | |
}) => { | |
const myReducer = createApiReducer(name); | |
class MyNewPage extends React { | |
componentDidMount() { | |
document.title = title; | |
if (onInit) { | |
onInit(); | |
} | |
} | |
render() { | |
const { isLoading, error, hasData, data } = this.props; | |
if (isLoading) return <LoadingPage />; | |
if (error) return <ErrorPage error={error} />; | |
if (!hasData) return <EmptyPage />; | |
return <Page data={data} />; | |
} | |
} | |
const mapStateToProps = (state) => ({ | |
isLoading, error, hasData, data, | |
}); | |
const mapDispatchToProps = (dispatch) => { | |
onInit: () => dispatch(onInit()); | |
}; | |
return { | |
component: connect(mapStateToProps, mapDispatchToProps)(MyNewPage), | |
reducers: [myReducer], | |
}; | |
}; | |
// index.js | |
const { reducers, component: AuditManagedPage } = createPage({ | |
Page: AuditPage, | |
onInit: fetchAudits, | |
}); | |
export reducers; | |
export default AuditManagedPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment