1. useQuery
useQuery.js
// @param url: string
function useQuery(url) {
const [data, setData] = useState(null);
const [isLoading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
(async () => {
setLoading(true);
try {
const { data } = await axios.get(url);
setData(data);
} catch (error) {
setError(error);
}
setLoading(false);
})();
}, []);
return { data, isLoading, error };
}
Usage
xxx.js
import useQuery from '../hooks/useQuery';
export const ArticleList = () => {
const { data, isLoading, error } = useQuery('/api/list')
...
}
2. useUser
import { useEffect } from 'react'
import Router from 'next/router'
import useSWR from 'swr'
const fetcher = (url) =>
fetch(url)
.then((r) => r.json())
.then((data) => {
return { user: data?.user || null }
})
export function useUser({ redirectTo, redirectIfFound } = {}) {
const { data, error } = useSWR('/api/user', fetcher)
const user = data?.user
const finished = Boolean(data)
const hasUser = Boolean(user)
useEffect(() => {
if (!redirectTo || !finished) return
if (
// If redirectTo is set, redirect if the user was not found.
(redirectTo && !redirectIfFound && !hasUser) ||
// If redirectIfFound is also set, redirect if the user was found
(redirectIfFound && hasUser)
) {
Router.push(redirectTo)
}
}, [redirectTo, redirectIfFound, finished, hasUser])
return error ? null : user
}
import { useUser } from '../lib/hooks'
import Layout from '../components/layout'
const Profile = () => {
const user = useUser({ redirectTo: '/login' })
return (
<Layout>
<h1>Profile</h1>
{user && (
<>
<p>Your session:</p>
<pre>{JSON.stringify(user, null, 2)}</pre>
</>
)}
</Layout>
)
}
export default
useUser({ redirectTo: '/login', redirectIfFound: true })