import React , { useState , useEffect } from 'react' ; import { useSelector , useDispatch } from 'react-redux' ; import Axios from 'axios' ; import CONSTANTS from '../_constants' ; import { IFPageOptions } from './useQuery' ; interface IFUseMutationReturn { data ? : any ; error : boolean ; fetching : boolean ; runBulkMutation : ( type : string , array : any [ ] ) => any ; runMutation : ( mutation ? : string , variables ? : any ) => any ; } const useMutation = ( query , variables , { shaper , pageOptions } ) => { const dispatch = useDispatch ( ) ; const permanentDomain = useSelector ( state => state . shop . domain ) ; const [ fetching , setFetching ] = useState ( false ) ; const [ error , setError ] = useState ( false ) ; const [ data , setData ] = useState ( ) ; param { GQLquery } mutation param { object } variables const runMutation = async ( mutation = query , vars = variables ) => { if ( fetching || ! permanentDomain ) { return false ; } try { setFetching ( true ) ; setError ( false ) ; const response = await Axios . post ( '/api/query' , { gql : mutation , shop : permanentDomain , variables : vars } ) ; if ( response . data ) { setData ( shaper ? shaper ( response ) : response ) ; } setFetching ( false ) ; return true ; } catch ( error ) { setFetching ( false ) ; setError ( true ) ; return false ; } } ; const runBulkMutation = ( type , array ) => { } ; useEffect ( ( ) => { dispatch ( { type : CONSTANTS . LOADING , payload : fetching } ) ; } , [ fetching ] ) ; const hookReturn = { data , error , fetching , runBulkMutation , runMutation } ; return hookReturn ; } ; export default useMutation ;