Skip to content

Instantly share code, notes, and snippets.

@popehiflo
Last active March 13, 2020 22:37
Show Gist options
  • Save popehiflo/83a829972a8c0dd05a79168b32697fe2 to your computer and use it in GitHub Desktop.
Save popehiflo/83a829972a8c0dd05a79168b32697fe2 to your computer and use it in GitHub Desktop.
Hook consumir API Rest con Fetch
import { useState, useEffect } from 'react';
//consumir API Rest con fetch
const useServices = () => {
const configServiceDefault = {
type: 'GET',
urls: '',
parameters: null,
isrequest: false
};
const[datas, setDatas] = useState(null);
const[config, setConfig] = useState(configServiceDefault);
useEffect(() => {
async function getData() {
try {
const response = await fetch(config.urls, {
method: `${config.type}`,
body: JSON.stringify(
config.parameters === null ? null : config.parameters
),
headers: {
'content-type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
if (data) {
setDatas(data);
}
}
} catch (error) {
}
}
if (config.isrequest) {
getData();
}
}, [config]);
return [datas, setConfig];
};
export default useServices;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment