Skip to content

Instantly share code, notes, and snippets.

@zachariahtimothy
Last active March 11, 2020 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachariahtimothy/cd8c1678dbbf8150f7b935cb2b497dfe to your computer and use it in GitHub Desktop.
Save zachariahtimothy/cd8c1678dbbf8150f7b935cb2b497dfe to your computer and use it in GitHub Desktop.
// In ActivityTypeForm.tsx
if (activityType === ActivityType.Mkt) {
return queryAndRenderActivityForm<GetActivityMarketQuery>({
activityQuery: GetActivityMarketDocument,
mutationDocument: SaveActivityMarketDocument,
queryVariables: activityId ? { id: activityId } : undefined,
onSaved,
onError,
Component: ActivityFormMarket,
mapInitialValues: (data) => {
return {
...data.activityMkt,
};
}
});
}
import { DocumentNode } from 'graphql';
import React from 'react';
import { useLazyQuery, useMutation } from '@apollo/react-hooks';
import { Loading, ErrorHandler } from '@mim/core';
import { Formik, FormikValues, FormikProps } from 'formik';
export interface queryAndRenderActivityFormProps<TData> {
activityQuery: DocumentNode;
mutationDocument: DocumentNode;
queryVariables?: any;
mapInitialValues: (data: TData) => FormikValues;
Component: React.ComponentType<FormikProps<FormikValues>>;
onSaved?: () => void;
onError?: (err: any) => void;
}
export const queryAndRenderActivityForm = <TData extends unknown>(props: queryAndRenderActivityFormProps<TData>) => {
const { activityQuery, queryVariables, Component, mapInitialValues, mutationDocument, onSaved, onError } = props;
// renderActivityFormByType should be used directly by ActivityTypeForm
// and will be called the same way on every render
const [query, { data, error, loading, called }] = useLazyQuery<TData>(activityQuery);
const [saveMutation] = useMutation(mutationDocument);
const handleSubmit = async (input: any) => {
try {
await saveMutation({ variables: { ...input } });
onSaved && onSaved();
} catch (err) {
onError && onError(err);
}
};
React.useEffect(() => {
if (queryVariables && Object.keys(queryVariables).length > 0) {
query({
variables: {
...queryVariables,
},
})
}
}, [activityQuery, queryVariables]);
if (called && loading) {
// return `Component Loading`
return <Loading />;
}
if (error) {
// return `Error`
return <ErrorHandler text={error.message} />;
}
return (
<Formik
initialValues={data ? mapInitialValues(data) : {}}
onSubmit={handleSubmit}
>
{formikBag => React.createElement(Component, { ...formikBag })}
</Formik>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment