Skip to content

Instantly share code, notes, and snippets.

@pbojinov

pbojinov/index.js

Last active Jul 10, 2020
Embed
What would you like to do?
// 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;
}
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