Skip to content

Instantly share code, notes, and snippets.

@bvodola
Created January 25, 2019 15:08
Show Gist options
  • Save bvodola/9b594ad0b7784c80c21b706c594c2d05 to your computer and use it in GitHub Desktop.
Save bvodola/9b594ad0b7784c80c21b706c594c2d05 to your computer and use it in GitHub Desktop.
import React from 'react';
import globals from '../../globals';
import axios from 'axios';
import Loading from '../Loading/Loading';
import VMasker from 'vanilla-masker';
class Form extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.getFormData = this.getFormData.bind(this);
this.setFormData = this.setFormData.bind(this);
this.state = {
isLoading: false,
form: {
...props.initialFormData,
},
}
}
async handleSubmit(ev) {
ev.preventDefault();
try {
this.setState({isLoading: true});
let {form} = this.state;
let {mutation, onSubmit} = this.props;
let formKeys = Object.keys(form);
let variables = '';
formKeys.forEach((k,i) => {
variables += `${k}: "${form[k]}"`
if(i < formKeys.length-1) variables += ', '
})
await axios.post(`/graphql`, {
query: `mutation{
${mutation}(${variables}){_id}
}`
})
let emptyForm = {}
formKeys.forEach(k => {emptyForm[k] = ''})
this.setState({form: emptyForm, isLoading: false})
onSubmit();
} catch(err) {
this.setState({isLoading: false})
}
}
setFormData(k,v) {
let {form} = this.state;
form[k] = v;
this.setState({form})
}
getFormData(k) {
return typeof this.state.form[k] !== 'undefined' ? this.state.form[k] : ''
}
componentDidMount() {
let maskedInputs = document.querySelectorAll(".masked");
for(let i=0; i<maskedInputs.length; i++) {
let el = maskedInputs[i];
VMasker(el).maskPattern(el.getAttribute('data-mask'));
}
}
render() {
const {children} = this.props;
const {isLoading} = this.state;
const childProps = {
getFormData: this.getFormData,
setFormData: this.setFormData,
isLoading,
};
return(
<form onSubmit={this.handleSubmit}>
{children(childProps)}
<Loading visible={isLoading} />
</form>
)
}
}
export default Form;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment