Next.js Discord

Discord Forum

I cannot detect that the cookie value has changed without refreshing the page.

Unanswered
Dwarf Crocodile posted this in #help-forum
Open in Discord
Avatar
Dwarf CrocodileOP
How can I detect the addition of a new cookie without refreshing the page?

3 Replies

Avatar
detect where?
Avatar
Dwarf CrocodileOP
I could not add it because the code exceeded the limit.

1- I log in and add the token to the cookie.

const submit = async (data) => {
        const { status, message, token } = await mutateAsync({
            email: data.email,
            password: data.password,
        });

        if (status) {
            setCookie("token", token?.value, {
                path: "/",
                maxAge: token?.expires_in,
                sameSite: "Strict",
            });
            toast.success(message);
            router.replace("/");
        } else {
            toast.error(message);
        }
    };


2- I get the token value in useSession and send a request to the api, the api returns me the user's values.

const token = getCookie("token") ?? null;

    const { data: session, isLoading } = useQuery({
        queryKey: ["session"],
        queryFn: async () => {
            const response = await fetch(`${SERVER_API_URL}/auth/me`, {
                method: "GET",
                headers: {
                    Accept: "application/json",
                    Authorization: `Bearer ${token}`,
                },
            });

            if (response.status === 200) {
                setIsAuthenticated(true);
            }

            return await response.json();
        },
        refetchOnWindowFocus: false,
        refetchOnMount: false,
        refetchOnWindowFocus: false,
    });


The problem is that I set the cookie after logging in, useSession does not see the existence of the cookie before refreshing the page. @gin
Initially there are no tokens in the cookies, when I log in I add the token to the cookies.

After refreshing the page, it detects the presence of the token, i.e. the cookie.