import * as React from 'react' ; import { WrappedComponentProps as IntlShapeProps , injectIntl } from 'react-intl' ; import { Event , Action } from '@client/forms' ; import { getBirthQueryMappings } from '@client/views/DataProvider/birth/queries' ; import { getDeathQueryMappings } from '@client/views/DataProvider/death/queries' ; import { Query } from '@client/components/Query' ; import { WatchQueryFetchPolicy } from 'apollo-client' ; interface IQueryProviderProps { event : Event ; action : Action ; payload ? : any ; fetchPolicy ? : WatchQueryFetchPolicy ; } type IProps = IQueryProviderProps & IntlShapeProps ; const QueryMapper = { [ Event . BIRTH ] : getBirthQueryMappings , [ Event . DEATH ] : getDeathQueryMappings } ; export const getQueryMapping = ( event , action ) => { return QueryMapper [ event ] && QueryMapper [ event ] ( action ) ; } ; export const QueryContext = React . createContext ( { loading : false , error : { } , data : { } , dataKey : '' } ) ; class QueryProviderComponent extends React . Component < IProps > { getMapping ( ) { const { event , action } = this . props ; return QueryMapper [ event ] && QueryMapper [ event ] ( action ) ; } render ( ) { const eventQueryMapping = this . getMapping ( ) ; if ( ! eventQueryMapping ) { return null ; } return ( < Query query = { eventQueryMapping . query } variables = { this . props . payload || { } } fetchPolicy = { this . props . fetchPolicy || 'cache-first' } > { ( { loading , error , data } ) => { return ( < QueryContext . Provider value = { { loading , error , data , dataKey : eventQueryMapping . dataKey } } > { this . props . children } < /QueryContext.Provider>); } } < /Query>); } } export const QueryProvider = injectIntl ( QueryProviderComponent ) ;