Skip to content

Instantly share code, notes, and snippets.

@abhimanyuPatil
Created July 25, 2022 17:27
Show Gist options
  • Save abhimanyuPatil/7067fceddf929f0d11c8df586e845ad2 to your computer and use it in GitHub Desktop.
Save abhimanyuPatil/7067fceddf929f0d11c8df586e845ad2 to your computer and use it in GitHub Desktop.
Submit Form Hook
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,
};
};
@abhimanyuPatil
Copy link
Author

abhimanyuPatil commented Jul 26, 2022

const {loading,submit} = submitFormHook()

submit(**yourEndPoint**,**yourData**)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment