Next.js Discord

Discord Forum

Zustand not saving state in next 13

Unanswered
Philippine Crocodile posted this in #help-forum
Open in Discord
Philippine CrocodileOP
So I am building a Frontend using Next 13 app directory. I have the login page at app/page.tsx. The code for it is bellow.

"use client";

import { useMediaQuery } from "@mantine/hooks";
import { useForm } from "@mantine/form";
import mediaQueryConstants from "@/constants/mediaQuerConstants";
import { LoginApi } from "@/api/auth";
import { useEffect, useState } from "react";
import LoginScreen from "@/Screens/Login/login";
import userDataStore from "@/Store/userData";

export default function LoginComponent() {
  const form = useForm({
    initialValues: {
      email: "",
      password: "",
    },

    validate: {
      email: (value) => (/^\S+@\S+$/.test(value) ? null : "Invalid email"),
      password: (value) =>
        value.length > 5
          ? null
          : "Please enter password with length greater than 5",
    },
  });

  const setUserData = userDataStore((state) => state.setUserData)
  const userData = userDataStore((state)=>state)

  const [isLoading, setLoading] = useState(false);

  const isLargeScreen = useMediaQuery(mediaQueryConstants.isLargeScreen);

  const handleSubmit = async (email: string, password: string) => {
    setLoading(true);
    const loginAttemptData = await LoginApi(email, password);
    if (!loginAttemptData.isSuccess)
      form.setErrors({
        [loginAttemptData.data.incorrectField]: loginAttemptData.message,
      });
    if (loginAttemptData.isSuccess) setUserData(loginAttemptData.data)
    setLoading(false);
  };

  useEffect(()=>console.log(userData),[userData])

  return (
    <LoginScreen
      handleSubmit={handleSubmit}
      form={form}
      isLoading={isLoading}
      isLargeScreen={isLargeScreen}
    />
  );
}

The state is being updated here as I am logging it and I can see it in the console.

Now when I try to navigate to admin/page.tsx which is a server side component the state does not persist and I see null data. I have tried making admin/page.tsx a client side component but it did not work

0 Replies