From e8b83dbcb91303fbab12fabb7fed4fee97846877 Mon Sep 17 00:00:00 2001 From: Ben Mitchinson Date: Fri, 27 Mar 2020 01:28:07 -0500 Subject: [PATCH] useAPI hook with demonstration on the login component --- pwa/src/components/Login.tsx | 7 +++++++ pwa/src/hooks/useApi.tsx | 26 ++++++++++++++++++++++++++ pwa/tsconfig.json | 1 + 3 files changed, 34 insertions(+) create mode 100644 pwa/src/hooks/useApi.tsx diff --git a/pwa/src/components/Login.tsx b/pwa/src/components/Login.tsx index c827349..5766b06 100644 --- a/pwa/src/components/Login.tsx +++ b/pwa/src/components/Login.tsx @@ -1,8 +1,11 @@ import React, { ReactElement } from 'react' +import useApi from '../hooks/useApi' import {InputItem, Button} from 'antd-mobile' import '../scss/Login.scss' export default function Login(): ReactElement { + const {response, error, isLoading} = useApi("") + return ( <>
@@ -19,6 +22,10 @@ export default function Login(): ReactElement {
+

Loading API Fetch: {isLoading.toString()}

+ {response && +

API Fetch Result: {JSON.stringify(response)}

+ } ) } diff --git a/pwa/src/hooks/useApi.tsx b/pwa/src/hooks/useApi.tsx new file mode 100644 index 0000000..4036246 --- /dev/null +++ b/pwa/src/hooks/useApi.tsx @@ -0,0 +1,26 @@ +import React from 'react' + + +const useFetch = (route: string) => { + const [response, setResponse] = React.useState(null); + const [error, setError] = React.useState(null); + const [isLoading, setIsLoading] = React.useState(false); + + React.useEffect(() => { + const fetchData = async () => { + setIsLoading(true); + try { + const res = await fetch("http://localhost:4000/" + route); + const json = await res.json(); + setResponse(json); + setIsLoading(false) + } catch (error) { + setError(error); + } + }; + fetchData(); + }, []); + return { response, error, isLoading }; +}; + +export default useFetch \ No newline at end of file diff --git a/pwa/tsconfig.json b/pwa/tsconfig.json index f2850b7..29f3cd7 100644 --- a/pwa/tsconfig.json +++ b/pwa/tsconfig.json @@ -6,6 +6,7 @@ "dom.iterable", "esnext" ], + "strictNullChecks": false, "allowJs": true, "skipLibCheck": true, "esModuleInterop": true,