1. useQuery

useQuery.js

  1. // @param url: string
  2. function useQuery(url) {
  3. const [data, setData] = useState(null);
  4. const [isLoading, setLoading] = useState(false);
  5. const [error, setError] = useState(null);
  6. useEffect(() => {
  7. (async () => {
  8. setLoading(true);
  9. try {
  10. const { data } = await axios.get(url);
  11. setData(data);
  12. } catch (error) {
  13. setError(error);
  14. }
  15. setLoading(false);
  16. })();
  17. }, []);
  18. return { data, isLoading, error };
  19. }

Usage
xxx.js

  1. import useQuery from '../hooks/useQuery';
  2. export const ArticleList = () => {
  3. const { data, isLoading, error } = useQuery('/api/list')
  4. ...
  5. }

2. useUser

  1. import { useEffect } from 'react'
  2. import Router from 'next/router'
  3. import useSWR from 'swr'
  4. const fetcher = (url) =>
  5. fetch(url)
  6. .then((r) => r.json())
  7. .then((data) => {
  8. return { user: data?.user || null }
  9. })
  10. export function useUser({ redirectTo, redirectIfFound } = {}) {
  11. const { data, error } = useSWR('/api/user', fetcher)
  12. const user = data?.user
  13. const finished = Boolean(data)
  14. const hasUser = Boolean(user)
  15. useEffect(() => {
  16. if (!redirectTo || !finished) return
  17. if (
  18. // If redirectTo is set, redirect if the user was not found.
  19. (redirectTo && !redirectIfFound && !hasUser) ||
  20. // If redirectIfFound is also set, redirect if the user was found
  21. (redirectIfFound && hasUser)
  22. ) {
  23. Router.push(redirectTo)
  24. }
  25. }, [redirectTo, redirectIfFound, finished, hasUser])
  26. return error ? null : user
  27. }
  1. import { useUser } from '../lib/hooks'
  2. import Layout from '../components/layout'
  3. const Profile = () => {
  4. const user = useUser({ redirectTo: '/login' })
  5. return (
  6. <Layout>
  7. <h1>Profile</h1>
  8. {user && (
  9. <>
  10. <p>Your session:</p>
  11. <pre>{JSON.stringify(user, null, 2)}</pre>
  12. </>
  13. )}
  14. </Layout>
  15. )
  16. }
  17. export default
  1. useUser({ redirectTo: '/login', redirectIfFound: true })