hooks#usePersistentState TypeScript Examples

The following examples show how to use hooks#usePersistentState. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: usePersistentState.tsx    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
TestComp: React.FC<TestCompProps> = ({
  storagekey,
  defaultVal,
  onclick
}) => {
  const [state, setState] = usePersistentState<any>(storagekey, defaultVal);

  return (
    <div>
      <div data-testid="state">{state}</div>
      <button data-testid="setState" onClick={(e) => onclick(setState)}>
        btn
      </button>
    </div>
  );
}
Example #2
Source File: AuthContextProvider.tsx    From crossfeed with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
AuthContextProvider: React.FC = ({ children }) => {
  const [authUser, setAuthUser] = useState<AuthUser | null>(null);
  const [token, setToken] = usePersistentState<string | null>('token', null);
  const [org, setOrg] = usePersistentState<
    Organization | OrganizationTag | null
  >('organization', null);
  const [showAllOrganizations, setShowAllOrganizations] = usePersistentState<
    boolean
  >('showAllOrganizations', false);
  const [feedbackMessage, setFeedbackMessage] = useState<{
    message: string;
    type: AlertProps['severity'];
  } | null>(null);
  const cookies = useMemo(() => new Cookies(), []);

  const logout = useCallback(async () => {
    const shouldReload = !!token;

    localStorage.clear();
    await Auth.signOut();
    cookies.remove('crossfeed-token', {
      domain: process.env.REACT_APP_COOKIE_DOMAIN
    });

    if (shouldReload) {
      // Refresh the page only if the token was previously defined
      // (i.e. it is now invalid / has expired now).
      window.location.reload();
    }
  }, [cookies, token]);

  const handleError = useCallback(
    async (e: Error) => {
      if (e.message.includes('401')) {
        // Unauthorized, log out user
        await logout();
      }
    },
    [logout]
  );

  const api = useApi(handleError);
  const { apiGet, apiPost } = api;

  const getProfile = useCallback(async () => {
    const user: User = await apiGet<User>('/users/me');
    setAuthUser({
      ...user,
      isRegistered: user.firstName !== ''
    });
  }, [setAuthUser, apiGet]);

  const setProfile = useCallback(
    async (user: User) => {
      setAuthUser({
        ...user,
        isRegistered: user.firstName !== ''
      });
    },
    [setAuthUser]
  );

  const refreshUser = useCallback(async () => {
    if (!token && process.env.REACT_APP_USE_COGNITO) {
      const session = await Auth.currentSession();
      const { token } = await apiPost<{ token: string; user: User }>(
        '/auth/callback',
        {
          body: {
            token: session.getIdToken().getJwtToken()
          }
        }
      );
      setToken(token);
    }
  }, [apiPost, setToken, token]);

  const extendedOrg = useMemo(() => {
    return getExtendedOrg(org, authUser);
  }, [org, authUser]);

  const maximumRole = useMemo(() => {
    return getMaximumRole(authUser);
  }, [authUser]);

  const touVersion = useMemo(() => {
    return getTouVersion(maximumRole);
  }, [maximumRole]);

  const userMustSign = useMemo(() => {
    return getUserMustSign(authUser, touVersion);
  }, [authUser, touVersion]);

  useEffect(() => {
    refreshUser();
    // eslint-disable-next-line
  }, []);

  useEffect(() => {
    if (!token) {
      setAuthUser(null);
    } else {
      getProfile();
    }
  }, [token, getProfile]);

  return (
    <AuthContext.Provider
      value={{
        user: authUser,
        token,
        setUser: setProfile,
        refreshUser,
        setOrganization: setOrg,
        currentOrganization: extendedOrg,
        showAllOrganizations: showAllOrganizations,
        setShowAllOrganizations: setShowAllOrganizations,
        login: setToken,
        logout,
        setLoading: () => {},
        maximumRole,
        touVersion,
        userMustSign,
        setFeedbackMessage,
        ...api
      }}
    >
      {api.loading && (
        <div className="cisa-crossfeed-loading">
          <div></div>
          <div></div>
        </div>
      )}
      {feedbackMessage && (
        <Snackbar
          open={!!feedbackMessage}
          autoHideDuration={5000}
          onClose={() => setFeedbackMessage(null)}
        >
          <Alert
            onClose={() => setFeedbackMessage(null)}
            severity={feedbackMessage.type}
          >
            {feedbackMessage.message}
          </Alert>
        </Snackbar>
      )}
      {children}
    </AuthContext.Provider>
  );
}
Example #3
Source File: Home.tsx    From iplocate with MIT License 4 votes vote down vote up
Home: React.FC = () => {
  const [currentIp, setCurrentIp] = useState<IP>();
  const [allIps, setAllIps] = usePersistentState<IP[]>("allIps", []);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [menuExpanded, setMenuExpanded] = useState(true);

  const onSearchIP = async (ip: string) => {
    setLoading(true);
    setError("");
    setAllIps((existing) => existing.filter((e) => e.traits.ipAddress !== ip));
    const params = new URLSearchParams({ ip });
    try {
      const ip = await request<IP>(`${endpoint}?${params}`);
      if (!(ip.location.latitude && ip.location.longitude)) {
        throw new Error("Unable to locate IP");
      }
      setCurrentIp(ip);
      setAllIps((allIps) => [ip, ...allIps]);
      setLoading(false);
    } catch (e) {
      setError(e.message);
      setLoading(false);
    }
  };

  const onRemoveIp = useCallback(
    (ip: IP) => {
      setAllIps((existing) =>
        existing.filter(
          (exist) => exist.traits.ipAddress !== ip.traits.ipAddress
        )
      );
    },
    [setAllIps]
  );

  const onToggleIpVisible = useCallback(
    (ip: IP) => {
      setAllIps((existing) =>
        existing.map((e) => ({
          ...e,
          hidden:
            e.traits.ipAddress === ip.traits.ipAddress ? !e.hidden : e.hidden,
        }))
      );
    },
    [setAllIps]
  );

  const onSetCurrentIP = useCallback(
    (ip: IP) => {
      if (window.matchMedia("(max-width: 450px)").matches) {
        setMenuExpanded(false);
      }
      setCurrentIp(ip);
    },
    [setCurrentIp]
  );

  return (
    <Wrapper>
      {loading && <Loading />}
      <CollapsableDialog
        title="IP Locate"
        collapsed={!!currentIp && allIps.length > 0}
        menuExpanded={menuExpanded}
        setMenuExpanded={setMenuExpanded}
      >
        {error && <ErrorMsg>{error}</ErrorMsg>}
        <IPForm onSubmit={(ip) => onSearchIP(ip)} />
        <IPMenu
          ips={allIps}
          onRemoveIp={onRemoveIp}
          onSetCurrentIp={onSetCurrentIP}
          onToggleIpVisible={onToggleIpVisible}
        />
      </CollapsableDialog>
      <Map
        selectedIP={currentIp}
        onSetSelectedIp={onSetCurrentIP}
        allIPs={allIps}
      />
    </Wrapper>
  );
}