Last active
January 3, 2023 20:49
-
-
Save vanxh/34ed59d24da4418a8ace538d528a8966 to your computer and use it in GitHub Desktop.
Conditional custom hook data fetching in NextJS using SWR
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
/* 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