P粉4289867442023-08-26 13:25:30
This code seems to create a problem/race condition because you are mixing two different ways of handling asynchronous Promise:
const user = await axios({ url: `${url}/api/user/login`, method: "POST", data: { username: username, password: password, }, "content-type": "application/json", }) .then((res) => { return res.data; }) .catch((err) => { if (err.response.data) { throw new Error(err.response.data); } else { return null; } return null; }); return user;
should be changed to this:
try { const user = await axios({ url: `${url}/api/user/login`, method: "POST", data: { username: username, password: password, }, "content-type": "application/json", }); return user.data; } catch (err) { if (err.response.data) { throw new Error(err.response.data); } else { return null; } }
Or like this:
axios({ url: `${url}/api/user/login`, method: "POST", data: { username: username, password: password, }, "content-type": "application/json", }).then((res) => { return res.data; }).catch((err) => { if (err.response.data) { throw new Error(err.response.data); } else { return null; } return null; });
P粉7072355682023-08-26 10:01:08
Add this component
to your App.js file:
function Auth({ children }) { const router = useRouter(); const { status } = useSession({ required: true, onUnauthenticated() { router.push("/sign-in"); }, }); if (status === "loading") { returnLoading ...; } return children; }
Now in your App function, instead of returning <Component {...pageProps} />
, first check the component
Does it have the auth
attribute, so you wrap it in <Auth>
to ensure that every component that requires a session will only be mounted after the session has finished loading (that's Why user is null
because the session is still loading)
{ Component.auth ? () : ( ); }
Finally, you add .auth = {}
to each page where you want to define a session (Home in your case)
const Home = () => { //.... } Home.auth = {};
This also helps redirect the user to the /sign-in
page