├── .github └── workflows │ └── codeql-analysis.yml ├── .gitignore ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.css ├── App.js ├── App.test.js ├── hooks.js ├── index.css ├── index.js ├── serviceWorker.js └── setupTests.js └── yarn.lock /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '27 23 * * 0' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 37 | # Learn more: 38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 39 | 40 | steps: 41 | - name: Checkout repository 42 | uses: actions/checkout@v3 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v2 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v2 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v2 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Use Fetch Hook 2 | 3 | TLDR; This repo shows how to build a custom hook to fetch and cache data! 4 | 5 | Here's [a deployed version](https://use-fetch-hook-example.netlify.app) of this example on Netlify! 6 | 7 | I wrote a piece about it on [Smashing Magazine](https://www.smashingmagazine.com/2020/07/custom-react-hook-fetch-cache-data/). 8 | 9 | ## Contents 10 | 11 | - [Installation](#installation) 12 | - [Run locally](#run-locally) 13 | 14 | ### Installation 15 | 16 | Clone repo: 17 | 18 | SSH: 19 | 20 | ```sh 21 | git clone git@github.com:ooade/use-fetch-hook.git 22 | cd use-fetch-hook 23 | ``` 24 | 25 | or 26 | 27 | HTTPS: 28 | 29 | ```sh 30 | git clone https://github.com/ooade/use-fetch-hook.git 31 | cd use-fetch-hook 32 | ``` 33 | 34 | ### Run locally 35 | 36 | Start a live-reload development server: 37 | 38 | ```sh 39 | yarn start 40 | ``` 41 | 42 | --- 43 | 44 | If you have any question, feel free to [reach out to me](https://twitter.com/_ooade)! 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "use-fetch-example", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.3.2", 8 | "@testing-library/user-event": "^7.1.2", 9 | "react": "^16.13.1", 10 | "react-dom": "^16.13.1", 11 | "react-scripts": "3.4.1" 12 | }, 13 | "scripts": { 14 | "start": "react-scripts start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ooade/use-fetch-hook/def5809d02b87fea56d35ec87cf9f06e7ee98dac/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ooade/use-fetch-hook/def5809d02b87fea56d35ec87cf9f06e7ee98dac/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ooade/use-fetch-hook/def5809d02b87fea56d35ec87cf9f06e7ee98dac/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | margin: 0; 4 | padding: 0; 5 | } 6 | 7 | body { 8 | padding: 1rem; 9 | transition: all 0.5s; 10 | } 11 | 12 | header { 13 | background: #253ec3; 14 | color: #fff; 15 | height: 80px; 16 | display: none; 17 | } 18 | 19 | a { 20 | color: #222; 21 | } 22 | 23 | .Form { 24 | display: flex; 25 | } 26 | 27 | .Form input { 28 | height: 40px; 29 | width: 350px; 30 | border: 1px solid #ddd; 31 | outline: none; 32 | padding: 0px 1rem; 33 | font-size: 16px; 34 | } 35 | 36 | .Form button { 37 | height: 40px; 38 | width: 100px; 39 | background: #222; 40 | border: none; 41 | cursor: pointer; 42 | color: #fff; 43 | } 44 | 45 | .query { 46 | padding-bottom: 2rem; 47 | } 48 | 49 | .loading { 50 | width: 20px; 51 | height: 20px; 52 | border-radius: 50%; 53 | display: inline-block; 54 | background: #222; 55 | position: relative; 56 | } 57 | 58 | .loading::before { 59 | position: absolute; 60 | content: ''; 61 | left: 0px; 62 | top: 0px; 63 | width: 100%; 64 | height: 100%; 65 | display: block; 66 | border-radius: 50%; 67 | margin-left: -5px; 68 | margin-top: -5px; 69 | border: 5px solid transparent; 70 | border-top-color: #222; 71 | border-bottom-color: #222; 72 | animation: spin 0.8s ease-out 0s infinite; 73 | } 74 | 75 | @keyframes spin { 76 | 0% { 77 | transform: rotate(0deg) scale(1.2); 78 | } 79 | 50% { 80 | transform: rotate(180deg) scale(1.2); 81 | } 82 | 100% { 83 | transform: rotate(360deg); 84 | } 85 | } 86 | 87 | main { 88 | padding: 1rem; 89 | } 90 | 91 | .article { 92 | line-height: 2; 93 | } 94 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import { useFetch } from './hooks'; 3 | import './App.css'; 4 | 5 | const App = () => { 6 | const [query, setQuery] = useState(''); 7 | 8 | const url = query && `https://hn.algolia.com/api/v1/search?query=${query}`; 9 | 10 | const { status, data, error } = useFetch(url); 11 | 12 | const handleSubmit = (e) => { 13 | e.preventDefault(); 14 | 15 | const query = e.target.search.value; 16 | if (query) { 17 | setQuery(query); 18 | e.target.search.value = ''; 19 | } 20 | }; 21 | 22 | const articles = data.hits; 23 | 24 | return ( 25 |
26 |
Hackernews Search
27 |
28 | 35 | 36 |
37 |
38 | {status === 'idle' && ( 39 |
Let's get started by searching for an article!
40 | )} 41 | {status === 'error' &&
{error}
} 42 | {status === 'fetching' &&
} 43 | {status === 'fetched' && ( 44 | <> 45 |
Search results for {query}
46 | {articles.length === 0 &&
No articles found! :(
} 47 | {articles.map((article) => ( 48 |
49 | 50 | {article.title} 51 | {' '} 52 | by {article.author} 53 |
54 | ))} 55 | 56 | )} 57 |
58 |
59 | ); 60 | }; 61 | 62 | export default App; 63 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /src/hooks.js: -------------------------------------------------------------------------------- 1 | import { useEffect, useRef, useReducer } from 'react'; 2 | 3 | export const useFetch = (url) => { 4 | const cache = useRef({}); 5 | 6 | const initialState = { 7 | status: 'idle', 8 | error: null, 9 | data: [], 10 | }; 11 | 12 | const [state, dispatch] = useReducer((state, action) => { 13 | switch (action.type) { 14 | case 'FETCHING': 15 | return { ...initialState, status: 'fetching' }; 16 | case 'FETCHED': 17 | return { ...initialState, status: 'fetched', data: action.payload }; 18 | case 'FETCH_ERROR': 19 | return { ...initialState, status: 'error', error: action.payload }; 20 | default: 21 | return state; 22 | } 23 | }, initialState); 24 | 25 | useEffect(() => { 26 | let cancelRequest = false; 27 | if (!url || !url.trim()) return; 28 | 29 | const fetchData = async () => { 30 | dispatch({ type: 'FETCHING' }); 31 | if (cache.current[url]) { 32 | const data = cache.current[url]; 33 | dispatch({ type: 'FETCHED', payload: data }); 34 | } else { 35 | try { 36 | const response = await fetch(url); 37 | const data = await response.json(); 38 | cache.current[url] = data; 39 | if (cancelRequest) return; 40 | dispatch({ type: 'FETCHED', payload: data }); 41 | } catch (error) { 42 | if (cancelRequest) return; 43 | dispatch({ type: 'FETCH_ERROR', payload: error.message }); 44 | } 45 | } 46 | }; 47 | 48 | fetchData(); 49 | 50 | return function cleanup() { 51 | cancelRequest = true; 52 | }; 53 | }, [url]); 54 | 55 | return state; 56 | }; 57 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' }, 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready 134 | .then(registration => { 135 | registration.unregister(); 136 | }) 137 | .catch(error => { 138 | console.error(error.message); 139 | }); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | --------------------------------------------------------------------------------