Created
June 12, 2020 23:08
-
-
Save matthewbdaly/d029c2f83e961ec324a9ba8062e65eb3 to your computer and use it in GitHub Desktop.
Revisions
-
matthewbdaly created this gist
Jun 12, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,53 @@ //@flow import React from 'react'; import useFetch from './Hooks/useFetch'; import marked from 'marked'; import './App.css'; type Data = { posts: Array<{ title: string, slug: string, content: string, name: Array<string> }> }; function App() { const url = `/graphql`; const query = `query { posts { title slug content tags { name } } }`; const [{data, loading, error}] = useFetch<Data>(url, query); if (loading) { return (<h1>Loading...</h1>); } if (error) { return (<h1>Error!</h1>); } const posts = data ? data.posts.map((item) => ( <div key={item.slug}> <h2>{item.title}</h2> <div dangerouslySetInnerHTML={{__html: marked(item.content)}} /> </div> ) ) : []; return ( <div className="App"> {posts} </div> ); } export default App; 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,41 @@ //@flow import { useCallback, useState, useEffect } from "react"; function useFetch<T>(url: string, query: string): [{ data: ?T, loading: boolean, error: boolean }, () => void] { const [data, setData]: [?T, ((?T => ?T) | ?T) => void] = useState(null); const [loading, setLoading]: [boolean, ((boolean => boolean) | boolean) => void] = useState(false); const [error, setError]: [boolean, ((boolean => boolean) | boolean) => void] = useState(false) const fetchData = useCallback(() => { setLoading(true); fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({query: query}) }).then(r => r.json()) .then((data) => { setData(data.data); setLoading(false); setError(false); }); }, [url, query]); useEffect(() => { fetchData(); }, [url, query, fetchData]); return [{ data: data, loading: loading, error: error }, fetchData]; } export default useFetch;