Skip to content

Instantly share code, notes, and snippets.

@chrisvxd
Last active December 6, 2018 20:47
Show Gist options
  • Save chrisvxd/b2bd271ddfda75e0eba2e6380efd4942 to your computer and use it in GitHub Desktop.
Save chrisvxd/b2bd271ddfda75e0eba2e6380efd4942 to your computer and use it in GitHub Desktop.
ApolloFormik component, for building typed Formik forms that mutate GraphQL via Apollo
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;
@chrisvxd
Copy link
Author

chrisvxd commented Dec 6, 2018

Usage:

import { Field } from 'formik';
import gql from 'graphql-tag';

const MY_FORM_MUTATION = gql`
    mutation mutateThing($email: string!) {
        mutateThing(email: $email) {
            email
        }
    }
`

class MyFormTyped extends ApolloFormik<{email: string}> {}

const MyForm = () => {
  return (
    <MyFormTyped
      initialValues={{ email: '' }}
      mutation={MY_FORM_MUTATION}
    >
      {formikBag => <>
        <Field type="email" name="email" placeholder="Email" />
        <button type="submit">Submit</button>
      </>}
    </MyFormTyped>
  )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment