Nikhil John
npm run generate
export function initTestAction() {
return {
type: TEST_ACTION_INIT,
};
}
export function testActionSuccess(data) {
return {
type: TEST_ACTION_SUCCESS,
data,
};
}
export function testActionError(error) {
return {
type: TEST_ACTION_ERROR,
error,
};
}
export const initialState = {
test: {
loading: false,
error: null,
data: null,
},
};
export const testContainerReducer = (state = initialState, action) =>
produce(state, draft => {
switch (action.type) {
case TEST_ACTION_INIT:
draft.test.loading = true;
draft.test.error = false;
break;
case TEST_ACTION_SUCCESS:
draft.test.loading = false;
draft.test.error = false;
draft.test.data = action.data;
break;
case TEST_ACTION_ERROR:
draft.test.loading = false;
draft.test.error = action.error;
// draft.test.data = null;
break;
}
});
loading | error | data | |
---|---|---|---|
INIT | true | null | null |
SUCCESS | false | null | action.data |
ERROR | false | action.error | null / existing data |
const makeSelectTestData = () =>
createSelector(
selectTestContainerDomain,
substate => substate.test.data,
);
const makeSelectTestLoading = () =>
createSelector(
selectTestContainerDomain,
substate => substate.test.loading,
);
const makeSelectTestError = () =>
createSelector(
selectTestContainerDomain,
substate => substate.test.error,
);
export function* fetchTestData() {
const requestURL = `/api/audiences`;
try {
const { data } = yield call(get, requestURL);
yield put(testActionSuccess(data));
} catch (err) {
yield put(testActionError(err));
yield put(
addMessageAction({
text: 'Whoops! Something went wrong. Please try again!',
}),
);
}
}
export default function* testContainerSaga() {
yield takeLatest(TEST_ACTION_INIT, fetchTestData);
}
/**
*
* TestContainer
*
*/
import React, { memo, useEffect } from 'react';
...
import { initTestAction } from './actions';
export function TestContainer({
loading,
error,
data: testData,
initiateDataFetch,
}) {
useInjectReducer({ key: 'testContainer', reducer });
useInjectSaga({ key: 'testContainer', saga });
useEffect(() => {
initiateDataFetch();
}, [!!testData]);
if (loading) {
return <div>LOADING.....</div>;
}
if (error) {
return <div>ERROR SCREEN/MESSAGE</div>;
}
return (
<div>
<Helmet>
<title>TestContainer</title>
<meta name="description" content="Description of TestContainer" />
</Helmet>
<FormattedMessage {...messages.header} />
<div>{testData}</div>
</div>
);
}
TestContainer.propTypes = {
initiateDataFetch: PropTypes.func.isRequired,
loading: PropTypes.bool,
error: PropTypes.bool,
data: PropTypes.string,
};
const mapStateToProps = createStructuredSelector({
loading: makeSelectTestLoading(),
error: makeSelectTestError(),
data: makeSelectTestData(),
});
function mapDispatchToProps(dispatch) {
return {
initiateDataFetch: () => dispatch(initTestAction()),
};
}
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
export default compose(
withConnect,
memo,
)(TestContainer);