Created
July 25, 2022 17:27
-
-
Save abhimanyuPatil/7067fceddf929f0d11c8df586e845ad2 to your computer and use it in GitHub Desktop.
Submit Form Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useState} from 'react'; | |
import AxiosConfig from '../services/axiosConfig'; //use own axios component | |
export type SubmitFunctionReturn = { | |
isSuccess: boolean; | |
data?: any | null; | |
error?: string | null; | |
}; | |
export const submitFormHook = () => { | |
const [loading, setLoading] = useState(false); | |
const api = new AxiosConfig(); | |
const submit = async ( | |
endpoint: string, | |
data: any, | |
): Promise<SubmitFunctionReturn> => { | |
setLoading(true); | |
let returnData = {isSuccess: true, data: null, error: null}; | |
await api | |
.postRequest(endpoint, data) | |
.then(res => { | |
setLoading(false); | |
returnData = {...returnData, data: res.data}; | |
}) | |
.catch(error => { | |
console.log('error', error); | |
setLoading(false); | |
returnData = {...returnData, isSuccess: false, error: error.message}; | |
}); | |
return returnData; | |
}; | |
return { | |
loading, | |
submit, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const {loading,submit} = submitFormHook()
submit(**yourEndPoint**,**yourData**)