KindeK
Kinde2y ago
11 replies
ro

Integrating with React, Vite, URQL

hey folks, im trying to intergrate Kinde auth with urql, and I'm running into some issues.

first off, here's the code:

export const GraphqlProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const auth = useKindeAuth();
  const [token, setToken] = useState<string>(
    JSON.parse(localStorage.getItem("kinde_token") ?? "{}").access_token ?? ""
  );

  const doRefreshToken = useCallback(async () => {
    // Check that auth is defined and getToken is a function
    if (auth == null || typeof auth.getToken !== "function") return;
    try {
      const newToken = await auth.getToken();
      if (newToken != null) {
        setToken(newToken);
      }
    } catch (error) {
      console.error("Error refreshing token:", error);
    }
  }, [auth]);

  useEffect(() => {
    doRefreshToken();
  }, [auth]);

  const graphqlClient = useMemo(() => {
    return new Client({
      url: `http://${baseGraphqlUrl}/graphql`,
      exchanges: [
        authExchange(async (utils) => {
          return {
            addAuthToOperation(operation) {
              return utils.appendHeaders(operation, {
                Authorization: `Bearer ${token}`,
              });
            },
            didAuthError(error, _operation) {
              return error.graphQLErrors.some(
                (e) => e.extensions?.code === "FORBIDDEN"
              );
            },
            refreshAuth: async () => {
              doRefreshToken();
            },
            willAuthError(_operation) {
              if (token == null || token === "") {
                return true;
              }
              return false;
            },
          };
        }),
        ...
      ],
    });
  }, [token]);

  return <Provider value={graphqlClient}>{children}</Provider>;
};

I keep running into undefined errors, where the output of the useKindeAuth hook is undefined
image.png
Was this page helpful?