Skip to content

Instantly share code, notes, and snippets.

@vanxh
Last active January 3, 2023 20:49
Show Gist options
  • Save vanxh/34ed59d24da4418a8ace538d528a8966 to your computer and use it in GitHub Desktop.
Save vanxh/34ed59d24da4418a8ace538d528a8966 to your computer and use it in GitHub Desktop.
Conditional custom hook data fetching in NextJS using SWR
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import useSWR from "swr";
import { getCookie } from "cookies-next";
import type { User } from "../lib/interfaces";
export default function useUser() {
const token = getCookie("token")?.toString();
const { data, error, mutate } = useSWR<{
user: User;
}>(token ? [`${process.env.NEXT_PUBLIC_API_URL}/v1/me`, token] : null);
return {
user: data?.user,
isLoading: !error && !data,
error,
mutate,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment