Learn how to use Async Await with common React Hooks
State
const [ APIData, setAPIData ] = useState<APIInterface>();
Effect
useEffect(() => {
const fetchAPIData = async () => {
const data = await getAPIData('none, one or more params')
setAPIData(data)
}
fetchAPIData()
// you may need to disable eslint rule for empty brackets
}, [])
API Call
const getAPIData = async (param: string) {
const response = await fetch(`/api/${param}`)
const data = await response.json();
return data;
}
State
const [ APIData, setAPIData ] = useState<APIInterface>();
Hook + API Call
const getAPIData = useCallback(async (param: string) => {
const response = await fetch(`/api/${param}`)
const data = response.json();
setAPIData(data);
}, [])