Last active
December 6, 2018 20:47
-
-
Save chrisvxd/b2bd271ddfda75e0eba2e6380efd4942 to your computer and use it in GitHub Desktop.
ApolloFormik component, for building typed Formik forms that mutate GraphQL via Apollo
This file contains 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 * as React from 'react'; | |
import { Mutation, ApolloConsumer } from 'react-apollo'; | |
import { ApolloClient } from 'apollo-client'; | |
import { Formik, FormikProps, Form } from 'formik'; | |
import { DocumentNode } from 'graphql'; | |
interface ApolloFormProps<T> { | |
afterSubmit?: (values: T) => void; | |
children: (formikBag: FormikProps<T>) => React.ReactNode; | |
initialValues: T; | |
mutation: DocumentNode; | |
} | |
class ApolloFormik<T> extends React.PureComponent<ApolloFormProps<T>> { | |
mutate = async (client: ApolloClient<any>, variables: T) => { | |
await client.mutate<void, T>({ mutation: this.props.mutation, variables }); | |
if (!!this.props.afterSubmit) { | |
this.props.afterSubmit(variables); | |
} | |
}; | |
render() { | |
const { children, initialValues } = this.props; | |
return ( | |
<ApolloConsumer> | |
{client => ( | |
<Formik | |
initialValues={initialValues} | |
onSubmit={values => { | |
this.mutate(client, values); | |
}} | |
render={(formikBag: FormikProps<T>) => ( | |
<Form> | |
{children(formikBag)} | |
</Form> | |
)} | |
/> | |
)} | |
</ApolloConsumer> | |
); | |
} | |
} | |
export default ApolloFormik; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: