-
-
Save brunosabot/a0a860d5324c91f5519744d6cd3883b4 to your computer and use it in GitHub Desktop.
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
export function useQuery(url) { | |
const [error, setError] = useState(false); | |
const [loading, setLoading] = useState(true); | |
const [serverData, setServerData] = useState({ name: "" }); | |
const loadData = useCallback(() => { | |
setLoading(true); | |
setError(false); | |
fetch(url) | |
.then((result) => result.json()) | |
.then((data) => { | |
setServerData(data); | |
setLoading(false); | |
}) | |
.catch(() => setError(true)); | |
}, [url]); | |
return { error, loading, data: serverData, loadData }; | |
} | |
export function MyRenderingComponent() { | |
const { error, loading, data, loadData } = useQuery( | |
"https://brunosabot.dev/api/hello/" | |
); | |
useEffect(loadData, []); | |
if (error) return <div>An error has occurred</div>; | |
if (loading) return <div>Loading...</div>; | |
return <div>{values.data.name}</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment