recoil#useRecoilValue JavaScript Examples

The following examples show how to use recoil#useRecoilValue. 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: CanvasBackground.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function CanvasBackground(props) {
  const setSelectedIds = useSetRecoilState(selectedIdsState);
  const backgroundColor = useRecoilValue(backgroundColorState);

  const handleClick = useCallback(() => {
    setSelectedIds([]);
  }, [setSelectedIds]);

  return (
    <View style={[StyleSheet.absoluteFill, { backgroundColor }]} onClick={handleClick} />
  );
}
Example #2
Source File: DetailPage.js    From app-personium-trails with Apache License 2.0 6 votes vote down vote up
function LocationDataURLViewChild({ __id, locationUrl }) {
  const { updateLocationACL } = useLocationACLSubscribe(__id, locationUrl);
  const aclStatus = useRecoilValue(locationACLStatusState(__id));
  const isLoading = aclStatus === 'loading';

  const refInput = useRef(null);

  useEffect(() => {
    updateLocationACL();
  }, []);

  const onClick = useCallback(() => {
    refInput.current.select();
    document.execCommand('copy');
  }, []);

  return (
    <Form.Field disabled={isLoading}>
      <label>This location is set as `{aclStatus}`</label>
      <Input
        fluid
        disabled={aclStatus === 'private'}
        ref={refInput}
        value={locationUrl}
        action={{
          color: 'teal',
          icon: 'copy',
          labelPosition: 'right',
          content: 'Copy',
          onClick: onClick,
        }}
      />
    </Form.Field>
  );
}
Example #3
Source File: PrivateRoute.js    From HealthBridge with GNU General Public License v3.0 6 votes vote down vote up
PrivateRoute = ({ component: Component, doc, ...rest }) => {
	const user = useRecoilValue(userAtom);

	return (
		<Route
			{...rest}
			render={(props) =>
				user ? (
					doc ? (
						user.type === "doctor" ? (
							<Component {...props} />
						) : (
							<Redirect to="/" />
						)
					) : user.type === "user" ? (
						<Component {...props} />
					) : (
						<Redirect to="/" />
					)
				) : (
					<Redirect to="/login" />
				)
			}
		/>
	);
}
Example #4
Source File: Navigation.jsx    From recoil-testing with MIT License 6 votes vote down vote up
export default function Navigation() {
    const recoilValue = useRecoilValue(textState);
    const Fetch = () => {
        fetch('/api')
        .then(data => console.log(data));
    }
    return (
        <div>
            <Suspense>
                <Fetch />
            </Suspense>
            <h1>This is my nested root component</h1>
            {recoilValue}
        </div>
    )
}
Example #5
Source File: TvShowDetails.jsx    From recoil-testing with MIT License 6 votes vote down vote up
Details = () => {

  const id = useRecoilValue(atoms.id);

  const tvShowResource = getTvDataResource(id).read();
  return (
    <div className="flex">
      <div>
        <h2>{tvShowResource.name}</h2>
        <div className="details">{tvShowResource.description}</div>
      </div>
      <div>
        <img
          src={`https://res.cloudinary.com/dqsubx7oc/image/upload/w_200/v1582908284/tv-shows/${id}.jpg`}
          alt={tvShowResource.name}
        />
      </div>
    </div>
  );
}
Example #6
Source File: TvShowDetails.jsx    From recoil-testing with MIT License 6 votes vote down vote up
Comments = () => {

  const id = useRecoilValue(atoms.id);

  const commentsResource = getCommentsResource(id).read();
  const comments = commentsResource.map(comment => (
    <div className="comment" key={comment.id}>
      <h4>{comment.title}</h4>
      <div className="text">{comment.text}</div>
    </div>
  ));

  return (
    <div className="flex flex-col comments">
      <h3>Comments</h3>
      {comments}
    </div>
  );
}
Example #7
Source File: Dashboard.js    From HealthBridge with GNU General Public License v3.0 6 votes vote down vote up
Dashboard = () => {
	const user = useRecoilValue(userAtom);
	return (
		<div className="Dashboard">
			<div className="container">
				<h1>Hi {user.name}</h1>
				<div className="cards">
					{services.map(({ imageAlt, title, image, desc, link }) => (
						<Card
							key={title}
							title={title}
							image={image}
							imageAlt={imageAlt}
							desc={desc}
							link={link}
						/>
					))}
					<div
						className="card"
						onClick={() => window.open("https://ambulance-on-demand.vercel.app")}>
						<div className="image">
							<img
								src={require("../assets/icons/ambulance.png")}
								alt="Ambulance"
							/>
						</div>
						<div className="content">
							<h4>Ambulance</h4>
							<p>
								A service to provide low latency and live location based ambulance service on demand.
							</p>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}
Example #8
Source File: Home.jsx    From react-recoil-jwt-authentication-example with MIT License 6 votes vote down vote up
function Home() {
    const auth = useRecoilValue(authAtom);
    const users = useRecoilValue(usersAtom);
    const userActions = useUserActions();

    useEffect(() => {
        userActions.getAll();
        
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <div>
            <h1>Hi {auth?.firstName}!</h1>
            <p>You're logged in with React + Recoil & JWT!!</p>
            <h3>Users from secure api end point:</h3>
            {users &&
                <ul>
                    {users.map(user =>
                        <li key={user.id}>{user.firstName} {user.lastName}</li>
                    )}
                </ul>
            }
            {!users && <div className="spinner-border spinner-border-sm"></div>}
        </div>
    );
}
Example #9
Source File: PrivateRoute.jsx    From react-recoil-jwt-authentication-example with MIT License 6 votes vote down vote up
function PrivateRoute({ component: Component, ...rest }) {
    const auth = useRecoilValue(authAtom);
    return (
        <Route {...rest} render={props => {
            if (!auth) {
                // not logged in so redirect to login page with the return url
                return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
            }

            // authorized so return component
            return <Component {...props} />
        }} />
    );
}
Example #10
Source File: Nav.jsx    From react-recoil-jwt-authentication-example with MIT License 6 votes vote down vote up
function Nav() {
    const auth = useRecoilValue(authAtom);
    const userActions = useUserActions();

    // only show nav when logged in
    if (!auth) return null;
    
    return (
        <nav className="navbar navbar-expand navbar-dark bg-dark">
            <div className="navbar-nav">
                <NavLink exact to="/" className="nav-item nav-link">Home</NavLink>
                <a onClick={userActions.logout} className="nav-item nav-link">Logout</a>
            </div>
        </nav>
    );
}
Example #11
Source File: useMoveItems.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function useMoveItems(func) {
  const [movingItemsSnapshot, setMovingItemsSnapshot] = useState([]);
  const movingItemIds = useRecoilValue(movingItemIdsState);

  const loadMovingItems = useLoadItems();
  const updateItemsPosition = useUpdateItems();

  const updateSnpashot = useCallback(async () => {
    const items = await loadMovingItems(movingItemIds);
    setMovingItemsSnapshot(items);
  }, [loadMovingItems, movingItemIds]);

  const { onMouseDown } = useMove((params) => {
    const { status, offset } = params;
    func(params);

    if (status === 'moving' && movingItemsSnapshot.length) {
      const newMovingItems = movingItemsSnapshot.map(item => {
        return {
          ...item,
          x: item.x + offset.x,
          y: item.y + offset.y,
        }
      });
      updateItemsPosition(newMovingItems);
    }
  });

  useEffect(() => {
    updateSnpashot();
  }, [movingItemIds, updateSnpashot]);

  return {
    onMouseDown
  }
}
Example #12
Source File: StateProvider.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
export default function StateProvider({ children }) {
  const authentication = useRecoilValue(authenticationState);

  useEffect(() => {
    const persistenceItems = createStore(authentication);
    store = persistenceItems.store;
    persistor = persistenceItems.persistor;

    store.dispatch({
      type: actionTypes.SET_AUTH,
      payload: authentication,
    });
    return () => {
      persistor.flush().then(() => {
        persistor.pause();
        store.dispatch({
          type: actionTypes.CLEAR_PATIENT_DATA,
        });
        store = null;
        persistor = null;
      });
    };
  }, [authentication]);

  if (!store) {
    return <LoadingIndicator />;
  }

  return (
    <Provider store={store}>
      <PersistGate
        loading={<LoadingIndicator />}
        persistor={persistor}
      >
        { children }
      </PersistGate>
    </Provider>
  );
}
Example #13
Source File: ItemInfoList.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function ItemInfoList() {
  const itemIds = useRecoilValue(itemIdsState);

  return (
    <View style={styles.root}>
      {itemIds.map(id => <ItemInfo key={`item-info-${id}`} id={id} />)}
    </View>
  );
}
Example #14
Source File: ItemInfo.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function ItemInfo({ id }) {
  const itemState = useRecoilValue(itemWithId(id));
  const { label, x, y } = itemState;

  return (
    <View style={styles.root}>
      {label ? <Text style={styles.label}>{label}</Text> : null}
      <Text style={styles.subLabel}>{`(x = ${x} y = ${y})`}</Text>
    </View>
  )
}
Example #15
Source File: Canvas.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function Canvas() {
  const ref = useRef();
  const itemIds = useRecoilValue(itemIdsState);
  const setLayoutState = useSetRecoilState(canvasLayoutState);

  const onLayout = ({
    nativeEvent: {
      layout: { x, y, width, height }
    }
  }) => setLayoutState({ x, y, width, height });

  return (
    <View style={styles.root} ref={ref} onLayout={onLayout}>
      <View style={styles.container}>
        <CanvasBackground />
        {itemIds.map(id => <CanvasItem key={`item-${id}`} id={id} />)}
        <Selection />
      </View>
    </View>
  );
}
Example #16
Source File: CanvasItem.js    From recoil-paint with MIT License 6 votes vote down vote up
export default function CanvasItem({ id }) {
  const [itemSnapshot, setItemSnapshot] = useState(null);
  const itemState = useRecoilValue(itemWithId(id));
  const setSelectedIds = useSetRecoilState(selectedIdsState);
  const updatePosition = useUpdateItem();

  const { onMouseDown } = useMove(({ status, origin, offset }) => {
    if (status === 'start') {
      setItemSnapshot(itemState);
    }

    if (status === 'moving' && itemSnapshot) {
      updatePosition({
        ...itemSnapshot,
        x: itemSnapshot.x + offset.x,
        y: itemSnapshot.y + offset.y,
      })
    }

    if (status === 'end') {
      setItemSnapshot(null);
      setSelectedIds(ids => {
        if (origin.metaKey || origin.shiftKey) {
          return [...ids, id];
        }
        return [id];
      });
    }
  });

  const Shape = createShape(itemState);
  if (!Shape) {
    return null;
  }

  return <Shape {...itemState} onMouseDown={onMouseDown} />;
}
Example #17
Source File: Medicine.js    From HealthBridge with GNU General Public License v3.0 5 votes vote down vote up
Medicine = () => {
	const token = useRecoilValue(tokenAtom);
	const [enteredName, setEnteredName] = useState("");
	const [commonNames, setCommonNames] = useState(null);

	const getBrandNames = () => {
		Axios.post(
			`https://eureka-scrapper-radioactive11.herokuapp.com/generic_name`,
			{
				generic_name: enteredName,
			},
			{
				headers: {
					Authorization: "Bearer " + token,
				},
			}
		)
			.then((res) => {
				console.log(res.data);
				setCommonNames(res.data);
			})
			.catch((err) => {
				console.log(err);
			});
	};

	return (
		<div className="Medicine">
			<div className="container">
				<div className="top">
					<h1>Common Medicine Names</h1>
					<p>
						Making brand names of medicines available to the patient
						by providing a generic name of the medicine, which are
						far cheaper and easily available.
					</p>
				</div>

				<div className="main">
					<div className="entered-name">
						<label htmlFor="medicine">Medicine Name</label>
						<input
							type="text"
							value={enteredName}
							onChange={(e) => setEnteredName(e.target.value)}
						/>
					</div>
					<button className="primary" onClick={() => getBrandNames()}>
						Get Results
					</button>
					{commonNames && (
						<div className="commons">
							<label htmlFor="commons">Common Medicines</label>
							<div className="result">
								<table>
									<thead>
										<tr>
											<th>Name</th>
											<th>General Price</th>
											<th>Source</th>
										</tr>
									</thead>
									<tbody>
										{commonNames.map((med) => (
											<tr>
												<td>{med.name}</td>
												<td>{med.price}</td>
												<td>{med.source}</td>
											</tr>
										))}
									</tbody>
								</table>
							</div>
						</div>
					)}
				</div>
			</div>
		</div>
	);
}
Example #18
Source File: useCubeStore.js    From minecraft-react with MIT License 5 votes vote down vote up
useCube = () => useRecoilValue($cubes)
Example #19
Source File: ProfilePage.js    From app-personium-trails with Apache License 2.0 5 votes vote down vote up
export function ProfilePage() {
  const login = useRecoilValue(isLogin);
  const token = useRecoilValue(tokens);
  const [introspection, setIntrospection] = useRecoilState(_introspection);
  const [userData, setUserData] = useState(null);
  const [xmlData, setXMLData] = useState(null);

  useEffect(() => {
    fetch(`${handler.boxUrl}secret.txt`, {
      headers: {
        Authorization: `Bearer ${handler.accessToken.access_token}`,
      },
    })
      .then(res => res.text())
      .then(text => setUserData(text));
    return () => setUserData(null);
  }, [token]);

  useEffect(() => {
    const { access_token } = handler.accessToken;
    statDirectory(`${handler.boxUrl}uploaded/`, access_token).then(res => {
      console.log(res);

      setXMLData(
        Array.from(res.entries()).map(([key, val]) => ({
          file: key,
          acl: Array.from(val.entries()).map(([key, val]) => ({
            principal: key,
            privilege: Array.from(val.keys()),
          })),
        }))
      );
    });
  }, handler.accessToken);

  return (
    <>
      <h1>Profile</h1>
      <Segment>
        <h3>Sample GET</h3>
        <p>Getting secret.txt</p>
        <p>{userData ? userData : 'loading'}</p>
      </Segment>

      <Segment>
        <h3>Sample XML</h3>
        <p>Getting /uploaded</p>
        <p>{xmlData ? JSON.stringify(xmlData) : 'loading'}</p>
      </Segment>

      <Segment>
        <h3>Tokens</h3>
        {login === true ? (
          <TokenView token={token} />
        ) : (
          <p>youre not logged in</p>
        )}
      </Segment>
      <Segment>
        <h3>Token introspection</h3>
        {introspection === null ? (
          <p>loading</p>
        ) : (
          <TokenIntrospect introspection={introspection} />
        )}
      </Segment>
    </>
  );
}
Example #20
Source File: LoginScreen.js    From discovery-mobile-ui with MIT License 5 votes vote down vote up
LoginScreen = () => {
  const baseUrl = useRecoilValue(baseUrlState);

  return (
    <SafeAreaView style={styles.root}>
      <StatusBar backgroundColor={Colors.primary} barStyle="dark-content" />
      <View style={styles.screen}>
        <View style={styles.topScreen}>
          <TouchableOpacity
            style={styles.navlink}
            onPress={() => Linking.openURL('https://syncfor.science/')}
          >
            <View style={styles.fullLogoContainer}>
              <FullLogo height={105} width={225} fill="black" />
            </View>
          </TouchableOpacity>
          <Suspense fallback={(<View style={styles.loading}><LoadingIndicator /></View>)}>
            <Login />
          </Suspense>
        </View>
        <View style={styles.midScreen} />
        <View style={styles.bottomScreen}>
          {!!baseUrl && <LoginButton baseUrl={baseUrl} />}
          <ResetAsyncStorageButton />
          <Text style={styles.powered}>Powered By</Text>
          <TouchableOpacity
            style={styles.navlink}
            onPress={() => Linking.openURL('https://dbmi.hms.harvard.edu')}
          >
            <Image
              style={styles.harvard}
              source={harvardLogo}
              resizeMode="contain"
            />
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.navlink}
            onPress={() => Linking.openURL('https://vermonster.com')}
          >
            <Image
              style={styles.vermonster}
              source={vermonsterLogo}
              resizeMode="contain"
            />
          </TouchableOpacity>
        </View>
      </View>
    </SafeAreaView>
  );
}
Example #21
Source File: LocationPage.js    From app-personium-trails with Apache License 2.0 5 votes vote down vote up
function LocationItem({ item }) {
  const timems = parseInt(item.startTime.match(/\/Date\((\d+)\)\//)[1]);
  const filename = `${'placeId' in item ? 's' : 'm'}_${timems}.json`;
  const folder = `${authState.boxUrl}locations/${getYMD(timems)}/`;
  const filepath = `${folder}${filename}`;

  const {
    setLocationACLPrivate,
    setLocationACLPublic,
  } = useLocationACLSubscribe(item.__id, filepath);
  const aclStatus = useRecoilValue(locationACLStatusState(item.__id));

  const onClick = useCallback(() => {
    if (aclStatus === 'loading') return;
    if (aclStatus === 'public') {
      setLocationACLPrivate();
    } else {
      setLocationACLPublic();
    }
  }, [aclStatus]);

  if ('placeId' in item) {
    return (
      <StayItem
        dat={item}
        key={`list-${item.__id}`}
        isPublic={aclStatus === 'public'}
        isLoading={aclStatus === 'loading'}
        onClick={onClick}
      />
    );
  } else {
    return (
      <MoveItem
        dat={item}
        key={`list-${item.__id}`}
        isPublic={aclStatus === 'public'}
        isLoading={aclStatus === 'loading'}
        onClick={onClick}
      />
    );
  }
}
Example #22
Source File: DetailPage.js    From app-personium-trails with Apache License 2.0 5 votes vote down vote up
function LocationRawDataViewChild({ __id }) {
  const locationUrl = useRecoilValue(locationURLFromId(__id));
  const [locationInfo, setLocationInfo] = useState({});

  useEffect(() => {
    let unmounted = false;
    fetch(locationUrl, {
      headers: {
        Authorization: `Bearer ${authState.accessToken.access_token}`,
      },
    })
      .then(res => res.json())
      .then(jsonDat => {
        if (!unmounted) setLocationInfo(jsonDat);
      });

    return function cleanup() {
      unmounted = true;
    };
  }, [locationUrl]);

  return (
    <Table>
      <Table.Header>
        <Table.Row>
          <Table.HeaderCell>Name</Table.HeaderCell>
          <Table.HeaderCell>Value</Table.HeaderCell>
        </Table.Row>
      </Table.Header>

      <Table.Body>
        {Object.entries(locationInfo).map(([key, val]) => {
          const _val = typeof val === 'object' ? JSON.stringify(val) : val;
          return (
            <Table.Row key={key}>
              <Table.Cell>{key}</Table.Cell>
              <Table.Cell style={{ overflowWrap: 'anywhere' }}>
                {_val}
              </Table.Cell>
            </Table.Row>
          );
        })}
      </Table.Body>
    </Table>
  );
}
Example #23
Source File: Login.jsx    From react-recoil-jwt-authentication-example with MIT License 5 votes vote down vote up
function Login({ history }) {
    const auth = useRecoilValue(authAtom);
    const userActions = useUserActions();

    useEffect(() => {
        // redirect to home if already logged in
        if (auth) history.push('/');

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // form validation rules 
    const validationSchema = Yup.object().shape({
        username: Yup.string().required('Username is required'),
        password: Yup.string().required('Password is required')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, setError, formState } = useForm(formOptions);
    const { errors, isSubmitting } = formState;

    function onSubmit({ username, password }) {
        return userActions.login(username, password)
            .catch(error => {
                setError('apiError', { message: error });
            });
    }

    return (
        <div className="col-md-6 offset-md-3 mt-5">
            <div className="alert alert-info">
                Username: test<br />
                Password: test
            </div>
            <div className="card">
                <h4 className="card-header">Login</h4>
                <div className="card-body">
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <div className="form-group">
                            <label>Username</label>
                            <input name="username" type="text" {...register('username')} className={`form-control ${errors.username ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.username?.message}</div>
                        </div>
                        <div className="form-group">
                            <label>Password</label>
                            <input name="password" type="password" {...register('password')} className={`form-control ${errors.password ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.password?.message}</div>
                        </div>
                        <button disabled={isSubmitting} className="btn btn-primary">
                            {isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
                            Login
                        </button>
                        {errors.apiError &&
                            <div className="alert alert-danger mt-3 mb-0">{errors.apiError?.message}</div>
                        }
                    </form>
                </div>
            </div>
        </div>
    )
}
Example #24
Source File: NewItemButton.js    From recoil-paint with MIT License 5 votes vote down vote up
export default function NewItemButton({ newShapeProps = {}, ...others }) {
  const [newItem, setNewItem] = useState(null);
  const setItemIds = useSetRecoilState(itemIdsState);
  const setSelectedIds = useSetRecoilState(selectedIdsState);
  const canvasLayout = useRecoilValue(canvasLayoutState);
  const createNewItem = useNewItem();
  const updatePosition = useUpdateItem();

  const { onMouseDown } = useMove(({ status, origin, offset }) => {
    if (status === 'start') {
      setNewItem(null);
      createNewItem({
        ...newShapeProps,
        x: origin.clientX - canvasLayout.x,
        y: origin.clientY - canvasLayout.y
      })
        .then(item => {
          setNewItem(item);
          setItemIds(items => [...items, item.id]);
          setSelectedIds([]);
        });
    }

    if (status === 'moving') {
      if (newItem) {
        updatePosition({
          ...newItem,
          x: origin.clientX + offset.x - canvasLayout.x,
          y: origin.clientY + offset.y - canvasLayout.y
        })
      }
    }

    if (status === 'end') {
      if (newItem) {
        setNewItem(null);
        setSelectedIds([newItem.id]);
      }
    }
  })



  return <Button {...others} onMouseDown={onMouseDown} />;
}
Example #25
Source File: Selection.js    From recoil-paint with MIT License 5 votes vote down vote up
export default function Selection() {
  const selectedIds = useRecoilValue(selectedIdsState);
  const selection = useRecoilValue(selectionBoundingBox);
  const setMovingItemIds = useSetRecoilState(movingItemIdsState);

  const { onMouseDown } = useMoveItems(({ status }) => {
    if (!selection) {
      return null;
    }

    if (status === 'start') {
      setMovingItemIds(selectedIds)
    }

    if (status === 'end') {
      setMovingItemIds([])
    }
  })

  if (!selection) {
    return null;
  }

  const { x, y, width, height } = selection;

  return (
    <>
      <View
        style={[styles.selection, {
          left: x,
          top: y,
          width,
          height
        }]}
        onMouseDown={onMouseDown}
      />
      <ResizeHandler />
    </>
  )
}
Example #26
Source File: PersoniumAppWrapper.js    From app-personium-trails with Apache License 2.0 4 votes vote down vote up
export function PersoniumAppWrapper(props) {
  const login = useRecoilValue(isLogin);
  const barInstalled = useRecoilValue($barInstalled);
  const [authInfo, setAuthInfo] = useRecoilState($authInfo);
  const setLocalMode = useSetRecoilState($localMode);
  const history = useHistory();

  useEffect(() => {
    console.log('mounted PersoniumAppWrapper');

    // ToDo: Set initialState in RecoilRoot
    const isLocalMode =
      //  false;
      location.hostname === 'localhost' || location.hostname === '127.0.0.1';

    setLocalMode(isLocalMode);

    // Boot Script
    const currentHash = location.hash.replace(/^#\/?/g, '#');
    console.log({ currentHash });

    let targetCell = null;

    if (currentHash.startsWith('#cell')) {
      // boot from Home App
      const [target] = currentHash
        .replace(/^#\/?/g, '')
        .split('&')
        .map(kv => kv.split('='))
        .filter(([k]) => k === 'cell');

      if (target) {
        targetCell = target[1];
        history.push('/');
      } else {
        throw `Something is wrong. Is hash wrong? ${currentHash}`;
      }
    } else {
      // boot directly
      // nextPath = currentHash;
      const lastLoginCell = localStorage.getItem(LS_LAST_LOGIN_CELL);
      targetCell = lastLoginCell ? lastLoginCell : null;
    }

    // oauth redirected
    const url = new URL(location.href);
    if (
      url.searchParams.has('cellUrl') &&
      url.searchParams.has('code') &&
      url.searchParams.has('state')
    ) {
      setAuthInfo({
        cellUrl: url.searchParams.get('cellUrl'),
        code: url.searchParams.get('code'),
        state: url.searchParams.get('state'),
      });
      url.searchParams.delete('cellUrl');
      url.searchParams.delete('code');
      url.searchParams.delete('state');
      window.history.replaceState({}, document.title, url.toString());
    } else {
      setAuthInfo(targetCell !== null ? { cellUrl: targetCell } : null);
    }

    // if (!targetCell) {
    //   // targetCell unknown
    //   setError({ message: 'Launch this app from your Home App again.' });
    //   return () => {};
    // }
  }, []);

  if (login && barInstalled === true) return props.children;

  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
      }}
    >
      <div style={{ flexGrow: 1 }} />
      {(() => {
        if (authInfo === null) return <PersoniumCellURL />;

        // attempt to login
        return (
          <>
            <PersoniumLoading />
            {(() => {
              if (!login) return <PersoniumAuthentication />;
              if (!barInstalled) return <PersoniumBarInstaller />;
            })()}
          </>
        );
      })()}
      <div style={{ flexGrow: 1 }} />
    </div>
  );
}
Example #27
Source File: PersoniumAppWrapper.js    From app-personium-trails with Apache License 2.0 4 votes vote down vote up
function PersoniumAuthentication() {
  const isLocalMode = useRecoilValue($localMode);
  const authInfo = useRecoilValue($authInfo);
  const setLogin = useSetRecoilState(isLogin);
  const setToken = useSetRecoilState(tokens);
  const setBarInstalled = useSetRecoilState($barInstalled);
  const [error, setError] = useState(null);

  useEffect(() => {
    let unmounted = false;
    let autoRefreshID = -1;

    const appUrlSplit = `${location.origin}${location.pathname}`.split('/');
    const appCellUrl = isLocalMode
      ? 'https://app-personium-trails.appdev.personium.io/'
      : `${appUrlSplit.slice(0, 3).join('/')}/`;
    // const appCellUrl = 'https://app-personium-trails.appdev.personium.io/';
    const targetCell = authInfo.cellUrl;

    const handler = isLocalMode
      ? new PersoniumLoginROPC(
          targetCell,
          localStorage.getItem('USERNAME_FOR_DEVELOPMENT'),
          localStorage.getItem('PASSWORD_FOR_DEVELOPMENT'),
          'https://app-personium-trails.appdev.personium.io/'
        )
      : new PersoniumLoginHandler(targetCell);

    // subscribe authentication state
    localStorage.setItem(LS_LAST_LOGIN_CELL, targetCell);
    console.log(appCellUrl, authInfo);
    handler
      .loginAsync(appCellUrl, authInfo)
      .catch(res => {
        // ToDo: change handling depending on situation.
        console.log(JSON.stringify(res));
        localStorage.removeItem(LS_LAST_LOGIN_CELL);
        if (res.status === 404) {
          setError({
            message: 'Authentication failed',
            body: `Cell not found: ${targetCell}`,
            // ToDo: refactoring
            bodyUrl: 'javascript: location.reload();',
          });
        } else {
          setError({
            message: 'Authentication failed',
            body: 'Please login from your Home App',
            bodyUrl: targetCell,
          });
        }
        return Promise.reject(res);
      })
      .then(authState => {
        // sined in successfully
        console.log('logged in');
        if (!unmounted) {
          setToken(authState.accessToken);
        }
        // start refreshing access_token (per 3000 sec)
        autoRefreshID = setInterval(() => handler.refreshAsync(), 3000 * 1000);

        // check bar installed;
        return authState
          .updateBoxUrl() // ToDo: refactoring Promise chain
          .then(() => {
            setBarInstalled(true);
          })
          .catch(res => {
            if (res.status === 403) {
              console.log('bar not installed');
              setBarInstalled(false);
            }
          });
      })
      .then(res => {
        if (!unmounted) {
          setLogin(true);
        }
      })
      .catch(reason => {
        console.log('error happened', reason);
      });

    return () => {
      // unsubscribe
      unmounted = true;
      if (autoRefreshID != -1) {
        clearInterval(autoRefreshID);
      }
    };
  }, [authInfo, isLocalMode, setToken, setLogin, setError, setBarInstalled]);

  return error ? (
    <>
      <h1>{error.message || 'Oops, you cannot sign in'}</h1>
      <p>
        <a href={error.bodyUrl}>{error.body || 'click'}</a>
      </p>
    </>
  ) : null;
}
Example #28
Source File: DashboardDoc.js    From HealthBridge with GNU General Public License v3.0 4 votes vote down vote up
DashboardDoc = ({ history }) => {
	const token = useRecoilValue(tokenAtom);
	const [user, setUser] = useRecoilState(userAtom);

	//State
	const [symptoms, setSymptoms] = useState("");
	const [medicine, setMedicine] = useState("");
	const [comments, setComments] = useState("");
	const [current, setCurrent] = useState("");

	const givePrescription = (pID, objID) => {
		Axios.post(
			`${process.env.REACT_APP_API_URL}/prescription/give`,
			{
				patientId: pID,
				symptoms,
				medicine,
				objID,
				comments,
				date: Date.now(),
			},
			{
				headers: {
					Authorization: "Bearer " + token,
				},
			}
		)
			.then((res) => {
				console.log(res.data, "give pres");
				// setUser(res.data);
				// localStorage.setItem("user", JSON.stringify(res.data));
			})
			.catch((err) => {
				console.error(err);
			});
	};

	useEffect(() => {
		Axios.get(`${process.env.REACT_APP_API_URL}/appointment/upcoming`, {
			headers: {
				Authorization: "Bearer " + token,
			},
		})
			.then((res) => {
				setUser(res.data);
				localStorage.setItem("user", JSON.stringify(res.data));
			})
			.catch((err) => {
				console.error(err);
			});
	}, []);

	const toggleCurrent = (_id) => {
		if (current === _id) {
			setCurrent("");
		} else {
			setCurrent(_id);
		}
	};
	return (
		<div className="DashboardDoc">
			<div className="container">
				<h1>Welcome Doctor</h1>
				<h3>Your Appointments</h3>
				<div className="cards">
					{user.appointments &&
						user.appointments.map((appointment) => (
							<div className="card" key={appointment._id}>
								<div className="head">
									Appointment No :{" "}
									{appointment.patient.substring(14)}
								</div>
								<div className="content">
									<h4> </h4>
									<p>Symptopms : {appointment.symptoms}</p>
								</div>

								<div className="box">
									<div className="box1"></div>
									<div className="box2"></div>
									<div className="box3"></div>
								</div>

								<div className="prescribe-input">
									<div className="edit-prescribe">
										<div className="head">Prescribe</div>{" "}
										<img
											onClick={() =>
												toggleCurrent(appointment._id)
											}
											src="https://img.icons8.com/cotton/2x/edit.png"
											alt="Edit Icon"
										/>
									</div>
									{appointment._id === current && (
										<React.Fragment>
											<label>Symptoms</label>
											<input
												type="text"
												value={symptoms}
												onChange={(e) =>
													setSymptoms(e.target.value)
												}
											/>
											<label>Medicine</label>
											<input
												type="text"
												value={medicine}
												onChange={(e) =>
													setMedicine(e.target.value)
												}
											/>
											<label>Comments</label>
											<input
												type="text"
												value={comments}
												onChange={(e) =>
													setComments(e.target.value)
												}
											/>
											<button
												className="primary"
												onClick={() =>
													givePrescription(
														appointment.patient,
														appointment._id
													)
												}>
												Update
											</button>
										</React.Fragment>
									)}
								</div>
								<div className="box">
									<div className="box1"></div>
									<div className="box2"></div>
									<div className="box3"></div>
								</div>
								{appointment.prescription && (
									<React.Fragment>
										<div className="head">Prescribed</div>
										<div className="prescribed">
											<div className="presc">
												<strong>Symptoms</strong> :{" "}
												{
													appointment.prescription
														.symptoms
												}{" "}
											</div>
											<div className="presc">
												<strong>Medicine</strong> :{" "}
												{
													appointment.prescription
														.medicine
												}{" "}
											</div>
											<div className="presc">
												<strong>Comments</strong> :{" "}
												{
													appointment.prescription
														.comments
												}{" "}
											</div>
										</div>
									</React.Fragment>
								)}
							</div>
						))}
				</div>
			</div>
		</div>
	);
}
Example #29
Source File: Home.js    From HealthBridge with GNU General Public License v3.0 4 votes vote down vote up
Home = ({ history }) => {
	const user = useRecoilValue(userAtom);
	console.log(user);
	const cta = () => {
		if (!user) {
			history.push("/SignUp");
		} else {
			if (user.type === "user") history.push("/dashboard");
			else history.push("/dashboardDoc");
		}
	};

	return (
		<div className="Home">
			<div className="container">
				{/* TOP SECTION  */}
				<div className="top">
					<div className="left">
						<h3 className="welcome">
							Welcome to{" "}
							<div className="logo">
								<h1>HealthBridge</h1>
							</div>
						</h3>
						<p>
							A service to connect patients and doctors.
							<br />Patients can book appointments 
							and can get themeselves checked online and get prescribed.
						</p>
						<button className="primary cta" onClick={() => cta()}>
							{user ? "Go To Dashboard" : "Get Started"}
						</button>
					</div>
					<div className="right">
						<img src={require("../assets/svg/doc3.svg")} alt="" />
					</div>
				</div>

				<div className="middle">
					<h2>Features</h2>
					<div className="cards">
						<div className="card">
							<img
								src={require("../assets/icons/heart.png")}
								alt="Heart Icon"
							/>
							<div className="content">
								<h4>Disease Predicition</h4>
								<p>
									Predicition of Breast Cancer and Pneumonia from X-RAY Scans and also
									patients can know the health status of their heart too.
								</p>
							</div>
						</div>
						<div className="card">
							<img
								src={require("../assets/icons/medicine.png")}
								alt="Heart Icon"
							/>
							<div className="content">
								<h4>General Name of Medicines</h4>
								<p>
								Making brand names of medicines available to the patient 
								by providing a generic name of the medicine, which are far cheaper and easily available
								</p>
							</div>
						</div>
						<div className="card">
							<img
								src={require("../assets/icons/doctor.png")}
								alt="Heart Icon"
							/>
							<div className="content">
								<h4>Book Appointment</h4>
								<p>
								Patients can book online appointments with a specific doctor and can get prescription afterwards
								</p>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}