Created
July 19, 2022 14:52
-
-
Save DonHuskini/74907cdf90be7733b4222448f6c7221b to your computer and use it in GitHub Desktop.
my file/folder structure
This file contains hidden or 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 { useEffect, useState } from "react"; | |
import axios from "axios"; | |
// | | |
// | | |
// |--services (all API fetching goes here) | |
// |----people.js | |
// |--hooks (all custom hooks goes here) | |
// |----useEndpoint.js | |
// |--pages | |
// |----index.jsx | |
// | | |
function fetchEndpoint() { | |
try { | |
const { data } = axios("/endpoint"); // {... count: 44, results:[ ... ] } | |
return data.results; | |
} catch (error) { | |
// log error to error managment software | |
logErrorSentry(error); | |
// throw error to UI for user feedback | |
throw Error("something"); | |
} | |
} | |
function useEndpoint() { | |
const [data, setData] = useState(); | |
const [error, setError] = useState(); | |
const [loading, setLoading] = useState(); | |
useEffect(() => { | |
async function getEndpoint() { | |
try { | |
setLoading(true); | |
const response = await fetchEndpoint(); | |
setData(response); | |
} catch (error) { | |
setError(true); | |
} finally { | |
setLoading(false); | |
} | |
} | |
getEndpoint(); | |
}, []); | |
return { | |
data, | |
error, | |
loading, | |
}; | |
} | |
function Comp() { | |
const { data, error, loading } = useEndpoint(); | |
if (error) return <div>error</div>; | |
if (loading) return <div>loading...</div>; | |
return ( | |
<div> | |
<pre>{JSON.stringify(data, null, 2)}</pre> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment