Last active
October 22, 2021 10:39
-
-
Save secretpray/7fbaa1b2f8035ef540f04e57995d1637 to your computer and use it in GitHub Desktop.
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
https://www.robinwieruch.de/react-hooks-fetch-data | |
useEffect(() => { | |
let didCancel = false; | |
async function fetchMyAPI() { | |
let url = 'http://something/' + productId; | |
let config = {}; | |
const response = await myFetch(url); | |
if (!didCancel) { // Ignore if we started fetching something else | |
console.log(response); | |
} | |
} | |
fetchMyAPI(); | |
return () => { didCancel = true; }; // Remember if we start fetching something else | |
}, [productId]); | |
~~~~~~~~~~~~~~~~~~ | |
useEffect(() => { | |
let didCancel = false; | |
async function fetchMyAPI() { | |
let url = 'http://something/' + productId; | |
let config = {}; | |
const response = await myFetch(url); | |
if (!didCancel) { // Ignore if we started fetching something else | |
console.log(response); | |
} | |
} | |
fetchMyAPI(); | |
return () => { didCancel = true; }; // Remember if we start fetching something else | |
}, [productId]); | |
~~~~~~~~~ | |
useEffect(() => { | |
async function fetchMyAPI() { | |
let url = 'http://something/' + productId; | |
let config = {}; | |
const response = await myFetch(url); | |
console.log(response); | |
} | |
fetchMyAPI(); | |
}, [productId]); | |
~~~~~~~~~ | |
useEffect(() => { | |
let didCancel = false; | |
async function fetchMyAPI() { | |
let url = 'http://something/' + productId; | |
let config = {}; | |
const response = await myFetch(url); | |
if (!didCancel) { // Ignore if we started fetching something else | |
console.log(response); | |
} | |
} | |
fetchMyAPI(); | |
return () => { didCancel = true; }; // Remember if we start fetching something else | |
}, [productId]); | |
~~~~~~~~~~~~~ | |
// Elsewhere | |
async function fetchWidgets() { | |
return await fetch('./api/widgets').then(r => r.json()) | |
} | |
// In my component: | |
function MyComponent() { | |
const [widgets, setWidgets] = useState([]); | |
// Need another async wrapper function to close over `setWidgets`? | |
useEffect(() => (async () => setWidgets(await fetchWidgets()))()); | |
~~~~~~~~~~~~~~~~ | |
function MyComponent() { | |
const [widgets, setWidgets] = useState([]); | |
async function unnecessaryApiWrapperClosureThatAddsLayersOfIndirection() { | |
setWidgets(await fetchWidgets()); | |
} | |
useEffect(() => unnecessaryApiWrapperClosureThatAddsLayersOfIndirection()); | |
~~~~~~~~~~~~~~~ | |
useEffect(() => (async () => { | |
try { | |
setWidgets(await fetchWidgets()); | |
catch e { | |
setError(e); | |
} | |
})()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment