Last active
July 10, 2020 18:33
-
-
Save pbojinov/362dcd57e040c52e691214a659af2aae to your computer and use it in GitHub Desktop.
React Data Fetching July 2019 - https://www.bitnative.com/2020/07/06/four-ways-to-fetch-data-in-react/
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
// Using SWR | |
import useSWR from 'swr' | |
function Profile () { | |
const { data, error } = useSWR('/api/user', fetcher) | |
if (error) return <div>failed to load</div> | |
if (!data) return <div>loading...</div> | |
return <div>hello {data.name}!</div> | |
} | |
// Using react-query | |
// --------------------------- | |
import React from "react"; | |
import { getUsers } from "./services/userService"; | |
import { useQuery } from "react-query"; | |
export default function ReactQueryDemo() { | |
const { data, isLoading, error } = useQuery("users", getUsers); | |
if (isLoading) return "Loading..."; | |
if (error) return "Oops!"; | |
return data[0].username; | |
} | |
// Using useFetch custom hook | |
// --------------------------- | |
import React from "react"; | |
import useFetch from "./useFetch"; | |
export default function HookDemo() { | |
const { data, loading, error } = useFetch("users"); | |
if (loading) return "Loading..."; | |
if (error) return "Oops!"; | |
return data[0].username; | |
} |
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
import { useState, useEffect, useRef } from "react"; | |
// This custom hook centralizes and streamlines handling of HTTP calls | |
export default function useFetch(url, init) { | |
const [data, setData] = useState(null); | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState(null); | |
const prevInit = useRef(); | |
const prevUrl = useRef(); | |
useEffect(() => { | |
// Only refetch if url or init params change. | |
if (prevUrl.current === url && prevInit.current === init) return; | |
prevUrl.current = url; | |
prevInit.current = init; | |
fetch(process.env.REACT_APP_API_BASE_URL + url, init) | |
.then(response => { | |
if (response.ok) return response.json(); | |
setError(response); | |
}) | |
.then(data => setData(data)) | |
.catch(err => { | |
console.error(err); | |
setError(err); | |
}) | |
.finally(() => setLoading(false)); | |
}, [init, url]); | |
return { data, loading, error }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment