Last active
March 13, 2020 22:37
-
-
Save popehiflo/83a829972a8c0dd05a79168b32697fe2 to your computer and use it in GitHub Desktop.
Hook consumir API Rest con Fetch
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, 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