Skip to content

Instantly share code, notes, and snippets.

@jeznag jeznag/submitform.tsx
Last active Aug 14, 2018

Embed
What would you like to do?
full submit button component
import React, { Component } from 'react';
import { Consumer as I18nConsumer } from '@App/I18nContext';
import { i18n } from 'i18next';
import { connect } from 'react-redux';
import AttemptSubmitActionCreator from '@App/RequestData/redux/action-creators/attemptSubmit';
import { IStoreState } from '@Redux/storeGenerator';
import { Mutation } from 'react-apollo';
import saveExportDataRequest from '@App/graphql/mutations/saveExportDataRequest';
import getAvailableOptions from '@App/graphql/queries/getAvailableOptions';
import {
canSubmit,
hasAttemptedSubmission,
transformDataForSubmission
} from '@App/graphql/submitDataTransformer';
interface IStateProps {
storeState: IStoreState;
}
interface IDispatchProps {
attemptSubmit: () => void;
}
const updateCache = (cache: any) => {
const { availableOptions } = cache.readQuery({ query: getAvailableOptions });
cache.writeQuery({
query: getAvailableOptions,
data: {
availableOptions: {
...availableOptions,
submitted: true
}
}
});
};
export class SubmitForm extends Component<IStateProps & IDispatchProps, {}> {
public render() {
return (
<I18nConsumer>
{(i18nInstance: i18n) => (
<div>
<Mutation mutation={saveExportDataRequest} update={updateCache}>
{(submitRequest, { loading }) => {
const possibleToSubmit = canSubmit(this.props.storeState);
const hasAttemptedSubmit = hasAttemptedSubmission(
this.props.storeState
);
return (
<button
className="btn btn-primary"
disabled={hasAttemptedSubmit && !possibleToSubmit}
onClick={() => {
if (!possibleToSubmit) {
return this.props.attemptSubmit();
}
const transformedData = transformDataForSubmission(
this.props.storeState
);
submitRequest({
variables: { input: transformedData }
});
}}
>
{loading
? i18nInstance.t(
'customer.data_export.request_data.loading'
)
: i18nInstance.t(
'customer.data_export.request_data.submit_form'
)}
</button>
);
}}
</Mutation>
</div>
)}
</I18nConsumer>
);
}
}
const mapStateToProps = (state: IStoreState) => {
return {
storeState: state
};
};
const mapDispatchToProps = (dispatch: (payload: any) => void) => ({
attemptSubmit: () => {
dispatch(AttemptSubmitActionCreator.attemptSubmit());
}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(SubmitForm);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.