tdc-js-modules
Version:
56 lines (55 loc) • 2.17 kB
text/typescript
import { useState } from 'react';
import axios from 'axios';
import { AxiosResponse } from 'axios';
import { UsePostConfigType, UsePostReturnType } from '../@types/usePost';
/**
* Hook usePost.
* Utilidad principal de la aplicación para postear data a APIs.
* Este hook entrega una intefaz funcional que permite:
* Consultar y transformar un la data traida de la API a través de una función transformadora.
* Indicar que tipo de datos retorna la consulta a través de un Genérico.
* Setear un valor inicial a la consulta.
* Llamar programaticamente una función post(body: any) cuando se necesite postear data.
* @param url: URL de la consulta
* @param config: Configuración de tipo UsePostConfigType
*/
function usePost<T = any>(url: string, config: UsePostConfigType = {}): UsePostReturnType<T> {
const [data, setData] = useState<T | any>(config.initialValue);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [response, setResponse] = useState<AxiosResponse | undefined>(undefined);
const user = sessionStorage.getItem('user');
/*let requestVariables = {method: 'POST', headers, signal};*/
const headers: { [key: string]: string } = {};
/* if (user) {
const parsed_user = JSON.parse(user);
headers['Authorization'] = `JWT ${parsed_user.jwt}`;
}*/
const post = (body = {}, cb: any = undefined) => {
setLoading(true);
headers['Content-Type'] = 'application/json';
axios
.post(url, body, { headers })
.then(res => {
if (config.transformFunction) {
setData(config.transformFunction(res));
} else {
setData(res);
}
setResponse(res);
setLoading(false);
if (res.status === 200) {
cb && cb();
}
/*console.log('HTTP-LOG POST', {url, body, data: res.data})*/
})
.catch(err => {
setError(err);
setLoading(false);
setResponse(err.response);
/*console.log('HTTP-LOG-ERROR POST', {url, body, error: err, response: err.response})*/
});
};
return { data, error, loading, response, post };
}
export default usePost;