Answer the question
In order to leave comments, you need to log in
How to do withAuth + swr?
Hi. I'm trying to hoc withAuth.js:
import useUser from "data/useUser";
import { useRouter } from 'next/router'
export default async function withAuth({ Component, pageProps }) {
const { loading, loggedIn, user } = await useUser();
const router = useRouter()
if (loading) return null
let newProps = Object.assign(pageProps, { user, loading, loggedIn })
if (loggedIn && user) return <Component {...newProps} />;
router.replace('/')
return null
}
//useUser.js
import useSWR from "swr";
import { getUser } from "requests/userApi";
export default function useUser() {
const { data, mutate, error } = useSWR("api_user", getUser, { revalidateOnFocus: true });
const loading = !data && !error;
const loggedIn = !error && data;
return {
loading,
loggedIn,
user: data,
mutate,
};
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question