Unnecessary reload needed to load new user data on login with apollo and graphql

Unnecessary reload needed to load new user data on login with apollo and graphql


0

so I had this problem for a while now and its driving me crazy. There was one answer on here however it did not help at all. So I am here to post my code to see if someone would be able to discern my stupidity.

Login component:

import React, { useState, useCallback, useEffect } from "react";
import { useMutation } from "@apollo/client";
import { useNavigate } from "react-router-dom";
import { LOGIN_MUTATION } from "../utils/Mutations";
import { useApolloClient } from "@apollo/client";
// import { GET_CURRENT_USER } from "../utils/Queries";

const Login = () => {
  const client = useApolloClient();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [remember, setRemember] = useState(false);
  const [loggedInState, setLoggedInState] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const [loginMutation] = useMutation(LOGIN_MUTATION);

  useEffect(() => {
    document.title = "Prihlásenie | LBC";
  }, []);

  const handleLogin = useCallback(
    async (e) => {
      e.preventDefault();
  
      try {
        setLoggedInState(true);
        const { data } = await loginMutation({
          variables: {
            email,
            password,
          },
        });
  
        const storage = remember ? localStorage : sessionStorage;
        storage.setItem("remember", JSON.stringify(remember));
        storage.setItem("token", data.login.token);
        storage.setItem("currentUser", JSON.stringify(data.login.allUserInfo));

        await client.resetStore();
  
        setSuccess("Prihlásenie prebehlo úspešne.");
        setError("");
        setTimeout(() => {
          navigate("/dashboard", { replace: true });
          window.location.reload();
        }, 1500);
      } catch (error) {
        setError("Nesprávne prihlasovacie údaje.");
        setSuccess("");
        setLoggedInState(false);
      }
    },
    [email, password, remember, loginMutation, navigate, client]
  );
  
  return (
    <>
      <div className="w-full fixed bg-transparent backdrop-blur-md">
        <p className="font-logos text-2xl text-center p-8 lg:hidden">LBC</p>
        <p className="font-subtitles text-lg text-center hidden lg:block lg:mt-8">
          Light Bringers Club
        </p>
      </div>

      <div className="flex flex-col lg:flex-row justify-center items-center w-full">
        <section className="flex flex-col items-center justify-center lg:w-1/2 h-[100vh]">
          <div>
            <p className="text-4xl text-center font-bold">Prihlásenie</p>
            <form
              onSubmit={handleLogin}
              className="mt-8 flex flex-wrap items-start"
            >
              <div className="w-[80%] mx-auto">
                <label className="text-sm text-left" htmlFor="email">
                  E-mail*
                </label>
                <input
                  className="w-full h-12 border border-black px-4 mt-2 outline-none"
                  type="email"
                  name="email"
                  id="email"
                  value={email}
                  minLength={8}
                  maxLength={53}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </div>

              <div className="w-[80%] mt-4 mx-auto">
                <label className="text-sm text-left" htmlFor="password">
                  Heslo*
                </label>

                <input
                  className="w-full h-12 border border-black px-4 mt-2 outline-none"
                  type="password"
                  name="password"
                  id="password"
                  value={password}
                  minLength={8}
                  maxLength={53}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                />
                {error && <p className="text-red-600 text-sm  mt-8">{error}</p>}
                {success && (
                  <p className="text-green-600 text-sm mt-8 flex">{success}</p>
                )}
              </div>

              <div className="w-[80%] mt-4 mx-auto">
                <label className="text-black">
                  <input
                    className="mt-4 rounded-none"
                    type="checkbox"
                    checked={remember}
                    onChange={(e) => setRemember(e.target.checked)}
                  />{" "}
                  Zapamätať si ma
                </label>
                <div className="font-bold text-red-600 mt-4 mb-4">
                  {loggedInState === true ? "Inicializácia..." : ""}
                </div>
              </div>

              <button
                type="submit"
                className="w-[80%] mx-auto h-12 mt-3 text-sm border-dotted border border-black hover:bg-black hover:text-white"
              >
                Prihlásiť sa
              </button>
            </form>

            <div className="mt-8 text-center font-bold">
              <p className="text-sm">
                Ešte nemáš účet?{" "}
                <a className="text-sm underline" href="/sign-up">
                  Registruj sa ZADARMO
                </a>
              </p>

              <p className="text-sm mt-4 font-normal">
                <a className="text-sm underline" href="/forgot-password">
                  Zabudol si heslo?{" "}
                </a>
              </p>
            </div>
          </div>
        </section>

        <section className="flex flex-col items-center justify-center lg:w-1/2 lg:pl-24 lg:pr-24 p-8 h-[100vh]">
          <div className="mt-0">
            <p className="text-4xl text-center font-bold">Pripoj sa k nám</p>{" "}
            <img
              src="https://i.gifer.com/embedded/download/3zh5.gif"
              className="mt-8 mb-8 mx-auto"
              alt="terminate"
              loading="eager"
            />
            <p className="text-lg text-center font-bold">
              Registruj sa teraz a získaj priamy prístup k VŠETKÉMU neplatenému
              LBC obsahu ZADARMO.
            </p>
            <br />
            <p className="text-lg text-center">
              <b>
                Chceš všetko čo LBC ponúka? Staň sa členom <br />a získaj
                prístup k VŠETKÉMU
              </b>{" "}
              obsahu, lekciám, návodom ako vybudovať vlastnú značku, eKnihám, a
              podcastom. <br /> <br /> Tiež získaš prístup k exkluzívnym zľavám
              na LBC & Apwire merch a eventy.
            </p>
          </div>
        </section>
      </div>
    </>
  );
};

export default Login;

Logout component:

import React from "react";
import { useNavigate } from "react-router-dom";
import { useApolloClient } from "@apollo/client";

const Logout = () => {
  const navigate = useNavigate();
  const client = useApolloClient();

  const logout = async () => {
    const remember = JSON.parse(localStorage.getItem("remember"));
    const storage = remember ? localStorage : sessionStorage;
    storage.clear();

    await client.clearStore();
    navigate("/", { replace: true });
  };

  return (
    <button
      onClick={logout}
      className="m-0 hover:text-red-600 text-gray-400 hidden lg:block"
    >
      Odhlásiť sa
    </button>
  );
};

export { Logout };

And I am fetching the user data in Dashboard component to load user info:

import React, { useEffect, useState } from "react";
import { useQuery } from "@apollo/client";
import { GET_CURRENT_USER } from "../utils/Queries";
import NavigationLayout from "../components/NavigationLayout";
import { ChangeName } from "../components/profile/index";
import { ChangePicture } from "../components/profile/index";

const Dashboard = () => {
  const [currentUser, setCurrentUser] = useState({});
  const [isChangeNameOpen, setIsChangeNameOpen] = useState(false);
  const [isChangePictureOpen, setIsChangePictureOpen] = useState(false);
  const user = currentUser;

  const openChangeName = () => {
    setIsChangeNameOpen(true);
  };

  const closeChangeName = () => {
    setIsChangeNameOpen(false);
  };

  const openChangePicture = () => {
    setIsChangePictureOpen(true);
  };

  const closeChangePicture = () => {
    setIsChangePictureOpen(false);
  };

  const {
    data: currentUserData,
    loading: userLoading,
    error: userError,
  } = useQuery(GET_CURRENT_USER, {
    fetchPolicy: "network-only",  
  });

  useEffect(() => {
    document.title = "Rozcestník | LBC";

    if (currentUserData) {
      setCurrentUser(currentUserData?.getCurrentUser);
    }
  }, [currentUserData]);

  if (userLoading) return <p className="p-8">Načítavam používateľa...</p>;
  if (userError)
    return <p className="p-8">Nastala chyba: {userError.message}</p>;

  const checkUser = () => {
    let userHasName = user?.name;
    if (user) {
      return (
        <>
          <p>
            Salve, <b>{user.name ? userHasName : user.email}</b>.
          </p>
        </>
      );
    } else {
      return <p>A ty čo tu robíš?</p>;
    }
  };

  const checkMembership = () => {
    if (currentUser.membership === true) {
      return (
        <p>
          Tvoje členstvo je momentálne <b className="text-green-600">platné.</b>{" "}
          😱
        </p>
      );
    } else {
      return (
        <p>
          Tvoje členstvo je momentálne <b className="text-red-600">neplatné.</b>{" "}
          🥲
        </p>
      );
    }
  };

  return (
    <div className="lg:flex">
      <NavigationLayout />
      <section className="w-full text-center flex items-center p-8 lg:justify-center flex-col h-screen mx-auto">
      <h1 className="font-bold mb-8 text-3xl top-8 sticky lg:absolute">Light Bringers Club</h1>
        <h2>{checkUser()}</h2>
        <span>{checkMembership()}</span>
        <img
          src={
            user
              ? user.profilePicture
              : "https://res.cloudinary.com/light-bringers/image/upload/v1694618538/zw4wjst1b4tvlndgv8gq.gif"
          }
          alt="profile_picture"
          className="w-32 h-32 rounded-full object-cover mt-10"
        />
        <div className="flex mt-8">
          <button className="underline" onClick={openChangePicture}>Zmeň si profilový obrázok</button>
          <ChangePicture isOpen={isChangePictureOpen} onClose={closeChangePicture} />
          <div className="ml-4">
            <button className="underline" onClick={openChangeName}>
              Pridaj, alebo si zmeň meno
            </button>
            <ChangeName isOpen={isChangeNameOpen} onClose={closeChangeName} />
          </div>
        </div>
        <div>
          {currentUser.membership === true ? (
            <div>
              <h3 className="font-bold mt-8">
                Teraz máš prístup ku všetkému obsahu na tejto stránke. 🥂🔥
              </h3>

              <p className="mt-8 text-gray-400 text-sm">
                Ak si to niekedy s členstvom rozmyslíš ty výmyselník, napíš mi
                na{" "}
                <a href="mailto:[email protected]" className="underline">
                  [email protected]
                </a>
              </p>
            </div>
          ) : (
            <div className="flex flex-col justify-center items-center">
              <h2 className="mt-14 text-6xl font-bold">Ešte nie si členom?</h2>
              <button
                onClick={""}
                className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 mt-14 mb-14 cursor-pointer"
              >
                Získaj prístup TERAZ
              </button>
            </div>
          )}
        </div>
      </section>
    </div>
  );
};

export default Dashboard;


Load 2 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *