import * as React from 'react' ; import { WrappedComponentProps as IntlShapeProps , injectIntl } from 'react-intl' ; import { Event , Action , IForm } from '@client/forms' ; import { getBirthMutationMappings } from '@client/views/DataProvider/birth/mutations' ; import { getDeathMutationMappings } from '@client/views/DataProvider/death/mutations' ; import { Mutation } from 'react-apollo' ; import { IApplication } from '@client/applications' ; interface IMutationProviderProps { event : Event ; action : Action ; form ? : IForm ; application ? : IApplication ; payload ? : any ; onCompleted : ( data : any ) => void ; onError ? : ( error : any ) => void ; } type IProps = IMutationProviderProps & IntlShapeProps ; const MutationMapper = { [ Event . BIRTH ] : getBirthMutationMappings , [ Event . DEATH ] : getDeathMutationMappings } ; export const getMutationMapping = ( event , action , payload ? , form ? , application ? ) => { return ( MutationMapper [ event ] && MutationMapper [ event ] ( action , payload , form , application ) ) ; } ; export const MutationContext = React . createContext ( { mutation : { } , loading : false , data : undefined } ) ; class MutationProviderComponent extends React . Component < IProps > { getMapping ( ) { const { event , action , payload , form , application } = this . props ; return getMutationMapping ( event , action , payload , form , application ) ; } render ( ) { const { onCompleted , onError } = this . props ; const eventMutationMapping = this . getMapping ( ) ; if ( ! eventMutationMapping ) { return null ; } return ( < Mutation mutation = { eventMutationMapping . mutation } variables = { eventMutationMapping . variables || null } onCompleted = { ( data ) => onCompleted ( data [ eventMutationMapping . dataKey ] ) } onError = { onError } > { ( submitMutation , { loading , data } ) => { return ( < MutationContext . Provider value = { { mutation : submitMutation , loading , data } } > { this . props . children } < /MutationContext.Provider>); } } < /Mutation>); } } export const MutationProvider = injectIntl ( MutationProviderComponent ) ;