react-cookie#useCookies JavaScript Examples

The following examples show how to use react-cookie#useCookies. 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: Travel.js    From wedding-website with MIT License 6 votes vote down vote up
function Travel() {
    const [cookies] = useCookies(["language"])

    const { Heading, SubHeading } = title[selectLanguage(cookies)]
    const travelItems = travel[selectLanguage(cookies)]

    return (
        <>
            <Header
                imageUrl={headerImg}
                Heading={Heading}
                SubHeading={SubHeading}
            />
            <Container fluid>
                {travelItems.map(
                    ({ Type, Title, Details, Address, Phone, link }, idx) => (
                        <Item
                            key={idx}
                            LeftMainTitle={Type}
                            LeftFirstSubTitle={Title}
                            RightFirstContact={Address}
                            RightSecondContact={Phone}
                            RightDetails={Details}
                            infoLink={link}
                        />
                    )
                )}
            </Container>
        </>
    )
}
Example #2
Source File: FAQ.js    From wedding-website with MIT License 6 votes vote down vote up
function FAQ() {
    const [cookies] = useCookies(["language"])

    const { Heading, SubHeading } = title[selectLanguage(cookies)]
    const faqItems = faqs[cookies.language]

    return (
        <>
            <Header
                imageUrl={headerImg}
                Heading={Heading}
                SubHeading={SubHeading}
            />
            <Container fluid>
                {faqItems.map(({ Question, Answer }, idx) => (
                    <div style={{ marginBottom: 100 }}>
                        <Item
                            key={idx}
                            LeftMainTitle={Question}
                            RightDetails={Answer}
                        />
                    </div>
                ))}
            </Container>
        </>
    )
}
Example #3
Source File: index.js    From wedding-website with MIT License 6 votes vote down vote up
App = () => {
    const { dispatch } = useContext(Store)

    const [cookies, setCookie] = useCookies(["language"])
    const language = get(cookies, ["language"], null)

    useEffect(() => {
        initializeApp(dispatch)
        if (isNull(language)) {
            setCookie("language", LANGUAGE.EN, { path: "/" })
        }
    }, [dispatch, setCookie, language])

    return (
        <BrowserRouter>
            <Switch>
                <Route path={"/auth"} component={Authentication} />
                <Route component={AppLayout} />
            </Switch>
        </BrowserRouter>
    )
}
Example #4
Source File: Footer.js    From wedding-website with MIT License 6 votes vote down vote up
Footer = () => {
    const [cookies] = useCookies(["language"])

    const { Content } = footer[selectLanguage(cookies)]

    return (
        <footer
            className={classNames(
                "text-center",
                "text-muted",
                "mt-auto",
                "py-3",
                styles.footer
            )}
        >
            <Content />
        </footer>
    )
}
Example #5
Source File: index.js    From bank-client with MIT License 6 votes vote down vote up
export default function ConstantCookie() {
  const [cookies, setCookie] = useCookies();
  const {
    location: { pathname },
  } = useSelector(stateSelector);

  useEffect(() => {
    if (cookies.accept) {
      ReactGA.initialize('UA-64684999-1');
      ReactGA.set({ anonymizeIp: true, page: pathname }); // GDPR
      ReactGA.pageview(pathname);
    }
  }, [cookies]);

  return (
    !cookies.accept && (
      <StyledConstantCookie>
        <div>
          <p>
            <FormattedMessage {...messages.description} />
          </p>
          <StyledConstantCookieActions>
            <Button>
              <a href="https://github.com/pietrzakadrian">
                <FormattedMessage {...messages.decline} />
              </a>
            </Button>
            <Button type="primary" onClick={() => setCookie('accept', true)}>
              <FormattedMessage {...messages.accept} />
            </Button>
          </StyledConstantCookieActions>
        </div>
      </StyledConstantCookie>
    )
  );
}
Example #6
Source File: Header.js    From wedding-website with MIT License 6 votes vote down vote up
function Header() {
    const [cookies] = useCookies(["language"])

    const HeaderContent = headers[selectLanguage(cookies)]

    return (
        <Jumbotron fluid className={styles.header}>
            <Container>
                <h1>
                    <HeaderContent />
                </h1>
            </Container>
        </Jumbotron>
    )
}
Example #7
Source File: RSVP.js    From wedding-website with MIT License 6 votes vote down vote up
function RSVP() {
    const { state } = useContext(Store)
    const [cookies] = useCookies(["language"])

    const {
        app: { user },
    } = state

    const { Heading, SubHeading, SubHeadingAuthenticated } = title[
        selectLanguage(cookies)
    ]

    return (
        <>
            <Header
                imageUrl={headerImg}
                Heading={Heading}
                SubHeading={
                    user.isAuthenticated
                        ? () => <SubHeadingAuthenticated user={user} />
                        : SubHeading
                }
            />
            {user.isAuthenticated && <RSVPForm />}
        </>
    )
}
Example #8
Source File: CookieInfo.js    From flotiq-blog with MIT License 6 votes vote down vote up
CookieInfo = ({ cookieText }) => {
    const [cookies, setCookie] = useCookies([COOKIE_KEY]);
    const [isShown, setIsShown] = useState(true);
    const isBrowser = () => typeof window !== 'undefined';

    const dismiss = () => {
        setCookie(COOKIE_KEY, 1);
    };

    useEffect(() => {
        setIsShown(true);
        setTimeout(() => {
            setIsShown(false);
        }, 15000);
    }, []);

    return (
        (isBrowser() && cookies && !cookies[COOKIE_KEY] && isShown)
            ? (
                <div className="cookie-info">
                    {/* eslint-disable-next-line react/no-danger */}
                    <div className="cookie-info-text" dangerouslySetInnerHTML={{ __html: cookieText }} />
                    <button aria-label="Close" className="cookie-info-close-btn" onClick={() => dismiss()}>
                        <img
                            alt="Close cookie info"
                            src={CloseCircle}
                        />
                    </button>
                </div>
            ) : null
    );
}
Example #9
Source File: MyPage.jsx    From relay_05 with MIT License 6 votes vote down vote up
export default function MainPage() {
  const [cookies, setCookie, removeCookie] = useCookies(["login"]);
  const user = cookies.login;
  const nickname = user.userName;
  const [checked, setChecked] = React.useState(false);
  const [image, setImage] = useState();

  const toggleChecked = () => {
    setChecked((prev) => !prev);
  };

  return (
    <Page>
      <MainMenu />
      <Container>
        {/* {!checked?<UserTable nickname={nickname} image={image}/> :  */}
        <EditTable nickname={nickname} checked={setChecked} image={setImage} />
        {/* <Switch checked={checked} onChange={toggleChecked} /> */}
      </Container>
    </Page>
  );
}
Example #10
Source File: MainPage.jsx    From relay_05 with MIT License 6 votes vote down vote up
export default function MainPage() {
  const [cookies, setCookie, removeCookie] = useCookies(["login"]);

  if (!cookies.login) {
    window.location.href = "/login";
  }

  return (
    <Page>
      <MainMenu />
      <Contents>
        <MainAd />
        <MainPosts />
      </Contents>
      <Dedan />
    </Page>
  );
}
Example #11
Source File: Registry.js    From wedding-website with MIT License 6 votes vote down vote up
function Registry() {
    const [cookies] = useCookies(["language"])

    const { Heading, SubHeading } = title[selectLanguage(cookies)]

    return (
        <>
            <Header
                imageUrl={headerImg}
                Heading={Heading}
                SubHeading={SubHeading}
            />
        </>
    )
}
Example #12
Source File: App.js    From web-frontend with MIT License 6 votes vote down vote up
function App() {
  const [cookies, setCookie, removeCookie] = useCookies(["webtoken"]);

  useEffect(() => {
    setCookie("view-menu", "true");
    return () => {};
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>Saving Cookies :)</p>
        <Other></Other>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}
Example #13
Source File: ThingsToDo.js    From wedding-website with MIT License 6 votes vote down vote up
function ThingsToDo() {
    const [cookies] = useCookies(["language"])

    const { Heading, SubHeading } = title[selectLanguage(cookies)]
    const thingsToDoItems = thingsToDo[selectLanguage(cookies)]

    return (
        <>
            <Header
                imageUrl={headerImg}
                Heading={Heading}
                SubHeading={SubHeading}
            />
            <Container fluid>
                {thingsToDoItems.map(({ Title, Details, link }, idx) => (
                    <Item
                        key={idx}
                        LeftMainTitle={Title}
                        RightDetails={Details}
                        infoLink={link}
                    />
                ))}
            </Container>
        </>
    )
}
Example #14
Source File: ChattingPage.jsx    From relay_05 with MIT License 5 votes vote down vote up
ChattingPage = ({ chattingTitle }) => {
  const [cookies, setCookie, removeCookie] = useCookies(["login"]);
  const [comments, setComments] = useState([]);
  const [ws, setWS] = useState(null);

  const addComment = useCallback(
    (data) => {
      const date = new Date();
      let newMessageData = {};
      if (data.length === 0) return;
      if (typeof data == "string") {
        newMessageData["nickname"] = user.userName;
        newMessageData["text"] = data;
        newMessageData["time"] =
          date.getFullYear() +
          "." +
          date.getMonth() +
          "." +
          date.getDate() +
          " " +
          date.getHours() +
          ":" +
          date.getMinutes();
      } else {
        newMessageData["nickname"] = data.nickname;
        newMessageData["text"] = data.message;
        newMessageData["time"] =
          date.getFullYear() +
          "." +
          date.getMonth() +
          "." +
          date.getDate() +
          " " +
          date.getHours() +
          ":" +
          date.getMinutes();
      }
      setComments([...comments, newMessageData]);
    },
    [comments]
  );
  const user = cookies.login;

  useEffect(() => {
    const ws = new WebSocket("ws://localhost:3555");
    ws.onmessage = (event) => {
      console.log("on message", event.data);
      let recData = JSON.parse(event.data);

      addComment(recData.data);
    };
    setWS(ws);
  }, []);

  useEffect(() => {
    if (!ws) return;
    ws.onmessage = (event) => {
      console.log("on message", event.data);
      let recData = JSON.parse(event.data);
      addComment(recData.data);
    };
  }, [ws, addComment]);

  return (
    <Page>
      <MainMenu />
      <ChattingBlock>
        <div className="chatting-header">
          <div className="chatting-title">{"채팅방"}</div>
        </div>
        <div className="content">
          {comments.map((comment, i) => (
            <ChattingContent comment={comment} key={i} />
          ))}
          <ChattingInput addComment={addComment} ws={ws} />
        </div>
      </ChattingBlock>
    </Page>
  );
}
Example #15
Source File: App.js    From lifebank with MIT License 5 votes vote down vote up
App = () => {
  const [currentUser, { logout }] = useUser()
  const [cookies, setCookie] = useCookies(['splash'])
  const [sideBarPosition, setSideBarPosition] = useState(true)

  const triggerSideBarPosition = () => {
    sideBarPosition ? setSideBarPosition(false) : setSideBarPosition(true)
  }

  return (
    <BrowserRouter>
      <MainContainer
        topbarContent={<TopBar user={currentUser} onLogout={logout} />}
        sidebarContent={
          <SideBar
            user={currentUser}
            onLogout={logout}
            triggerSideBarPosition={triggerSideBarPosition}
          />
        }
        sideBarPosition={sideBarPosition}
      >
        <Grid container justify="center" alignItems="center">
          <SplashIntro
            skipHandling={(cookie) => {
              const d = new Date()
              d.setMonth(d.getMonth() + 3)
              setCookie(cookie, undefined, {
                expires: d
              })
            }}
            cookie={cookies.splash}
          />
          <Switch>
            {routes.map(({ path, component: Component, ...args }) => (
              <Route key={`path-${path}`} path={path} {...args}>
                <Component />
              </Route>
            ))}
            <Redirect to="/not-found" />
          </Switch>
        </Grid>
      </MainContainer>
    </BrowserRouter>
  )
}
Example #16
Source File: ChattingInput.jsx    From relay_05 with MIT License 5 votes vote down vote up
ChattingInput = ({ addComment, ws }) => {
  const [cookies, setCookie, removeCookie] = useCookies(["login"]);

  const user = cookies.login;
  const [message, setMessage] = useState("");
  const [nickname, setNickname] = useState(user.userName);

  const send = (nickname, message) => {
    console.log(`전송: ${nickname}, ${message}`);
    // 서버로 message 이벤트 전달 + 데이터와 함께
    let sendData = {
      event: "req",
      data: { nickname: nickname, message: message },
    };
    ws.send(JSON.stringify(sendData));
  };

  const onChange = useCallback((e) => {
    setMessage(e.target.value);
  });

  const handleInput = (e) => {
    if (e.key === "Enter" && message.length !== 0) {
      console.log("handleInput---message", message);
      addComment(message);
      setMessage("");
    }
  };

  const onSubmit = useCallback(
    (e) => {
      addComment(message);
      setMessage("");
      send(nickname, message);
      e.preventDefault();
      e.target.reset();
    },
    [addComment, message]
  );

  return (
    <ChattingInputBlock>
      <form className="ChattingInput" onSubmit={onSubmit}>
        <TextField
          id="input"
          label="Write comment!"
          variant="outlined"
          onChange={onChange}
          onKeyUp={handleInput}
          style={{ width: "90%" }}
        />
        <button type="submit">
          <SendIcon id="send" />
        </button>
      </form>
    </ChattingInputBlock>
  );
}
Example #17
Source File: GsignIn.js    From yasn with MIT License 5 votes vote down vote up
export default function GsignIn(props) {
  const [cookies, setCookie] = useCookies(['']);

  let auth2;
  const googleLoginBtn = useRef(null);

  useEffect(() => {
    googleSDK();
  });

  const prepareLoginButton = () => {
    auth2.attachClickHandler(
      googleLoginBtn.current,

      {},
      (googleUser) => {
        let profile = googleUser.getBasicProfile();

        let AuthCookie = {
          Token: googleUser.getAuthResponse().id_token,
          ID: profile.getId(),
          Name: profile.getName(),
          Email: profile.getEmail(),
        };

        setCookie('userCookie', AuthCookie, { path: '/' });

        window.location.reload();
      },
      (error) => {
        alert(JSON.stringify(error.reason, undefined, 2));
      }
    );
  };

  const googleSDK = () => {
    window['googleSDKLoaded'] = () => {
      window['gapi'].load('auth2', () => {
        auth2 = window['gapi'].auth2.init({
          client_id: GoogleClientId,
          hosted_domain: 'daiict.ac.in',
          cookiepolicy: 'single_host_origin',
          prompt: 'select_account',
          scope: 'profile email',
        });
        prepareLoginButton();
      });
    };

    (function (d, s, id) {
      var js,
        fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {
        return;
      }
      js = d.createElement(s);
      js.id = id;
      js.src = 'https://apis.google.com/js/platform.js?onload=googleSDKLoaded';
      fjs.parentNode.insertBefore(js, fjs);
    })(document, 'script', 'google-jssdk');
  };

  return <div ref={googleLoginBtn}>{props.element}</div>;
}
Example #18
Source File: Schedule.js    From wedding-website with MIT License 5 votes vote down vote up
function Schedule() {
    const [cookies] = useCookies(["language"])

    const { Heading, SubHeading } = title[selectLanguage(cookies)]
    const scheduleItems = schedule[cookies.language]

    return (
        <>
            <Header
                imageUrl={headerImg}
                Heading={Heading}
                SubHeading={SubHeading}
            />
            <Container fluid>
                {scheduleItems.map(
                    (
                        {
                            Title,
                            Date,
                            Time,
                            Location,
                            locationLink,
                            Address,
                            Details,
                            mapLink,
                        },
                        idx
                    ) => (
                        <Item
                            key={idx}
                            LeftMainTitle={Title}
                            LeftFirstSubTitle={Date}
                            LeftSecondSubTitle={Time}
                            RightMainTitle={() => (
                                <a
                                    href={locationLink}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                >
                                    <Location />
                                </a>
                            )}
                            RightFirstContact={() => (
                                <a
                                    href={mapLink}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                >
                                    <Address />
                                </a>
                            )}
                            RightDetails={Details}
                        />
                    )
                )}
            </Container>
        </>
    )
}
Example #19
Source File: Other.jsx    From web-frontend with MIT License 5 votes vote down vote up
Other = () => {
  const [cookies, setCookie, removeCookie] = useCookies(["webtoken"]);
  return (
    <div>
      <p>La cookie view-menu vale: {cookies["view-menu"]}</p>
    </div>
  );
}
Example #20
Source File: Details.js    From wedding-website with MIT License 5 votes vote down vote up
function Details() {
    const [cookies] = useCookies(["language"])

    const { Title, Date, Location, hashtag, locationLink } = details[
        selectLanguage(cookies)
    ]
    return (
        <section>
            <Container>
                <Row>
                    <Col className={styles.details}>
                        <h1 className={styles.announcement}>
                            <Title />
                        </h1>
                        <h1 className={styles.date}>
                            <Date />
                        </h1>
                        <h2 className={styles.location}>
                            <a
                                href={locationLink}
                                target="_blank"
                                rel="noopener noreferrer"
                            >
                                <Location />
                            </a>
                        </h2>
                        <h3 className={styles.hashtag}>
                            <a
                                href={`https://www.instagram.com/explore/tags/${hashtag}`}
                                target="_blank"
                                rel="noopener noreferrer"
                            >
                                {`#${hashtag}`}
                            </a>
                        </h3>
                    </Col>
                </Row>
            </Container>
        </section>
    )
}
Example #21
Source File: RSVPForm.js    From wedding-website with MIT License 4 votes vote down vote up
function RSVPForm() {
    const { state, dispatch } = useContext(Store)
    const [cookies] = useCookies(["language"])

    const [showConfirmation, setShowConfirmation] = useState(false)

    const {
        app: {
            user: { email },
            rsvp: { allowed, confirmed },
        },
    } = state

    const {
        AlertNoEmail,
        submitButtonText,
        updateButtonText,
        yesLabel,
        noLabel,
        lampollaLabel,
        tortosaLabel,
        otherLabel,
        otherLabelExtra,
        WeddingFormHeader,
        NumberOfGuestsLabel,
        zeroLabel,
        NumberOfGuestsHelp,
        TransportationLabel,
        TransportationHelp,
        OriginLabel,
        OriginHelp,
        SongsLabel,
        SongsHelp,
        DinnerFormHeader,
        DinnerGuestsLabel,
        DinnerGuestsHelp,
        AlertRSVPUpdated,
    } = rsvpForm[selectLanguage(cookies)]

    useEffect(() => {
        if (email) {
            fetchUserRSVPInformation(email, dispatch)
        }
    }, [email, dispatch])

    const submitForm = (values, actions) => {
        const { setSubmitting, setStatus } = actions
        putUserRSVPInformation(
            { email, ...values },
            setSubmitting,
            setStatus,
            setShowConfirmation,
            dispatch
        )
    }

    if (isNull(allowed)) {
        return (
            <Container>
                <Col className={styles.intro}>
                    <Alert variant="info">
                        <AlertNoEmail />
                    </Alert>
                </Col>
            </Container>
        )
    }

    // wedding values
    const weddingMaxGuests = get(allowed, ["Wedding", "MaxGuests"])
    const weddingConfirmedGuests = get(confirmed, [
        "Wedding",
        "ConfirmedGuests",
    ])
    const weddingSongs = get(confirmed, ["Wedding", "Songs"])
    const weddingNeedBus = get(confirmed, ["Wedding", "NeedBus"])
    const weddingOrigin = get(confirmed, ["Wedding", "Origin"])

    // rehearsal values
    const rehearsalMaxGuests = get(allowed, ["Rehearsal", "MaxGuests"])
    const rehearsalConfirmedGuests = get(confirmed, [
        "Rehearsal",
        "ConfirmedGuests",
    ])

    const buttonText = isUndefined(weddingConfirmedGuests)
        ? submitButtonText
        : updateButtonText

    return (
        <Formik
            validationSchema={schema}
            initialValues={{
                weddingGuests: weddingConfirmedGuests || 0,
                rehearsalGuests: rehearsalConfirmedGuests || 0,
                needBus: weddingNeedBus || NO,
                origin: weddingOrigin || TORTOSA,
                songs: weddingSongs || "",
            }}
            onSubmit={submitForm}
        >
            {({
                handleSubmit,
                handleChange,
                handleBlur,
                values,
                touched,
                isSubmitting,
                errors,
                status,
            }) => (
                <Form
                    noValidate
                    onSubmit={handleSubmit}
                    className={styles.form}
                >
                    <div className="text-center">
                        <h5 className="text-muted">
                            <WeddingFormHeader />
                        </h5>
                    </div>
                    <Form.Group controlId="controlIdWeddingGuests">
                        <Form.Label>
                            <NumberOfGuestsLabel />
                        </Form.Label>
                        <Form.Control
                            name="weddingGuests"
                            as="select"
                            value={values.weddingGuests}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={
                                touched.weddingGuests && errors.weddingGuests
                            }
                        >
                            {range(0, weddingMaxGuests + 1).map(idx => (
                                <option
                                    label={idx === 0 ? zeroLabel : idx}
                                    value={idx}
                                    key={idx}
                                >
                                    {idx === 0 ? zeroLabel : idx}
                                </option>
                            ))}
                        </Form.Control>
                        <Form.Text className="text-muted">
                            <NumberOfGuestsHelp />
                        </Form.Text>
                    </Form.Group>
                    <Form.Group controlId="controlIdNeedBus">
                        <Form.Label>
                            <TransportationLabel />
                        </Form.Label>
                        <Form.Control
                            name="needBus"
                            as="select"
                            value={values.needBus}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={touched.needBus && errors.needBus}
                        >
                            <option label={yesLabel} value={YES}>
                                {yesLabel}
                            </option>
                            <option label={noLabel} value={NO}>
                                {noLabel}
                            </option>
                        </Form.Control>
                        <Form.Text className="text-muted">
                            <TransportationHelp />
                        </Form.Text>
                    </Form.Group>
                    {values.needBus === YES && (
                        <Form.Group controlId="controlIdOrigin">
                            <Form.Label>
                                <OriginLabel />
                            </Form.Label>
                            <Form.Control
                                name="origin"
                                as="select"
                                value={values.origin}
                                onChange={handleChange}
                                onBlur={handleBlur}
                                isInvalid={touched.origin && errors.origin}
                            >
                                <option label={tortosaLabel} value={TORTOSA}>
                                    {tortosaLabel}
                                </option>
                                <option label={lampollaLabel} value={LAMPOLLA}>
                                    {lampollaLabel}
                                </option>
                                <option
                                    label={`${otherLabel} - ${otherLabelExtra}`}
                                    value={OTHER}
                                >{`${otherLabel} - ${otherLabelExtra}`}</option>
                            </Form.Control>
                            <Form.Text className="text-muted">
                                <OriginHelp />
                            </Form.Text>
                        </Form.Group>
                    )}
                    <Form.Group controlId="controlIdWeddingSongs">
                        <Form.Label>
                            <SongsLabel />
                        </Form.Label>
                        <Form.Control
                            name="songs"
                            as="textarea"
                            rows="3"
                            value={values.songs}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={touched.songs && errors.songs}
                        />
                        <Form.Text className="text-muted">
                            <SongsHelp />
                        </Form.Text>
                    </Form.Group>
                    <div className="text-center mt-5">
                        <h5 className="text-muted">
                            <DinnerFormHeader />
                        </h5>
                    </div>
                    <Form.Group controlId="controlIdRehearsalGuests">
                        <Form.Label>
                            <DinnerGuestsLabel />
                        </Form.Label>
                        <Form.Control
                            name="rehearsalGuests"
                            as="select"
                            value={values.rehearsalGuests}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={
                                touched.rehearsalGuests &&
                                errors.rehearsalGuests
                            }
                        >
                            {range(0, rehearsalMaxGuests + 1).map(idx => (
                                <option
                                    label={idx === 0 ? `0 - ${zeroLabel}` : idx}
                                    value={idx}
                                >
                                    {idx === 0 ? `0 - ${zeroLabel}` : idx}
                                </option>
                            ))}
                        </Form.Control>
                        <Form.Text className="text-muted">
                            <DinnerGuestsHelp />
                        </Form.Text>
                    </Form.Group>
                    <Button
                        className="mt-5"
                        variant="primary"
                        type="submit"
                        size="lg"
                        disabled={isSubmitting}
                        block
                    >
                        {buttonText}
                    </Button>
                    {status && (
                        <Alert variant="danger" className="mt-4">
                            {status}
                        </Alert>
                    )}
                    <Alert
                        variant="success"
                        className="mt-4"
                        onClose={() => setShowConfirmation(false)}
                        show={showConfirmation}
                    >
                        <AlertRSVPUpdated />
                    </Alert>
                </Form>
            )}
        </Formik>
    )
}
Example #22
Source File: nearme.jsx    From howlongistheline.org with Mozilla Public License 2.0 4 votes vote down vote up
function Index({ history }) {
    {/*Initialise props*/ }
    const [clientLocation, setclientLocation] = useCookies(['location']);
    const [nearestShops, setnearestShops] = useState([]);
    const [loading, setLoading] = useState(false);
    const [loadingMessage, setLoadingMessage] = useState("Getting your location...");
    const [search, setSearch] = useState("");
    const [searchResult, setSearchResult] = useState([]);
    const [loadingCardList, setLoadingCardList] = useState({ [""]: false });
    const [isOpen, setIsOpen] = useState(false);
    const [reportId, setReportId] = useState("");

    useEffect(() => {
        checkClientLocation()
    }, [])

    useEffect(() => {
        let isCancelled = false;
        try {
            if (!isCancelled) {
                Tracker.autorun(function () {
                    if (!isCancelled) {
                        if (search == "") {
                        }
                        else {
                            var searchArray = search.split(/(\s+)/).filter( e => e.trim().length > 0)
                            let allResults = []
                            searchArray.forEach((word)=>{
                                allResults.push(LocationsIndex.search(word).fetch())
                            })
                            var flatten = _.flatten(allResults)
                            var removeDup = _.unique(flatten, false, function(item, k, v){
                                return item._id;
                            });
                            console.log(removeDup)
                            setSearchResult(removeDup)
                        }
                    }
                })
            }
        } catch (e) {
            if (!isCancelled) {
                throw e;
            }
        }
        return function cleanup() {
            isCancelled = true;
        }
    }, [search])

    function distance(lat1, lon1, lat2, lon2, unit) {
        if ((lat1 == lat2) && (lon1 == lon2)) {
            return 0;
        }
        else {
            var radlat1 = Math.PI * lat1 / 180;
            var radlat2 = Math.PI * lat2 / 180;
            var theta = lon1 - lon2;
            var radtheta = Math.PI * theta / 180;
            var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
            if (dist > 1) {
                dist = 1;
            }
            dist = Math.acos(dist);
            dist = dist * 180 / Math.PI;
            dist = dist * 60 * 1.1515;
            if (unit == "K") { dist = dist * 1.609344 }
            if (unit == "N") { dist = dist * 0.8684 }
            return dist;
        }
    }

    function checkClientLocation() {
        if (clientLocation.location != undefined) {
            if ((new Date().getTime() - new Date(clientLocation.location.time).getTime()) / 1000 < 300) {
                if (nearestShops.length == undefined || nearestShops.length <= 1) {
                    fetchNearestShops()
                } else {
                    // console.log(nearestShops)
                }
            } else { getClientLocation() }
        } else { getClientLocation() }
    }

    function getClientLocation() {
        setLoading(true)
        var options = {
            enableHighAccuracy: true,
            timeout: 30000,
            maximumAge: 300000
        };

        function success(position) {
            console.log("CLT longitude: ")
            console.log(position.coords.longitude)
            console.log("CLT latitude: ")
            console.log(position.coords.latitude)
            setclientLocation('location', { longitude: position.coords.longitude, latitude: position.coords.latitude, time: new Date() });
            fetchNearestShops(position.coords.latitude, position.coords.longitude);
        }

        function error(err) {
            setLoading(false)
            console.log("nm location failure")
            toast("Can't get current location, please try a different browser if this continues")
            console.warn(`ERROR(${err.code}): ${err.message}`);
        }

        navigator.geolocation.getCurrentPosition(success, error, options);

    }

    function fetchNearestShops(latitude, longitude) {
        console.log("CLT updating nearest stores")
        var lat;
        var long;
        if (clientLocation.location == undefined) {
            lat = latitude;
            long = longitude;
        } else {
            lat = clientLocation.location.latitude;
            long = clientLocation.location.longitude;
        }
        Meteor.call('locations.findnearby', { lat, long }, (err, result) => {
            if (result) {
                setLoading(false)
                setnearestShops(result)
            } else {
                console.log(err)
            }
        }
        );
        setLoadingMessage("Loading nearby stores...")
    }

    function renderList() {
        if (loading) {
            return (<Card>
                <ProgressBar indeterminate />
                {loadingMessage}
            </Card>)
        }
        if (search == "") {
            return nearestShops.map((location) => {
                return renderCard(location)
            }
            )
        }
        else {
            return searchResult.map((location) => {
                return renderCard(location)
            })
        }
    }

    function Line(people) {
        if(people) {
            if(people === 1) {
                return "There was 1 person in line"
            } else {
                return `There were ${getDisplayedLineLength(people)} people in line`
            }
        } else {
            return "There was no line"
        }
    }

    function renderCard(location) {
        var Indicator = "green"
        switch (true) {
            case (location.line == undefined):
                Indicator = "green"
                break
            case (location.line <= 20 && location.line >= 0):
                Indicator = "green"
                break
            case (location.line <= 35 && location.line > 20):
                Indicator = "orange"
                break
            case (location.line > 35):
                Indicator = "red"
                break
        }
        var updateNumber = location.line;
        return (
            <Card key={location._id} style={{ backgroundColor: "white" }}>
                <ListItem style={{ fontSize: 20, fontWeight: "bold" }} modifier="nodivider">
                    {location.name}
                    <div className="right">
                        <Button onClick={() => {
                            // history.push('/duplicated?id=' + location._id)
                            setIsOpen(true)
                            setReportId(location._id)
                        }}>
                            <i className="fas fa-exclamation-triangle" />
                        </Button>
                    </div>
                </ListItem>
                <ListItem modifier="nodivider" expandable>
                    <div className="left">
                        <Icon style={{ paddingRight: 20 }} icon="map-marker-alt" /> {location.address}
                    </div>
                    <div className="expandable-content">
                        <img style={{ maxHeight: 200 }} src={"https://howlongistheline.org/maps/" + location.coordinates[1] + "," + location.coordinates[0] + ",K3340"} />
                    </div>

                </ListItem>
                <ListItem modifier="nodivider">
                    <div className="center" style={{ color: Indicator }}>
                        {Line(location.line)} {moment(location.lastUpdate).fromNow()}.
                    </div>
                    <div className="right">
                        <Button onClick={() => { history.push('/stocks?id=' + location._id) }}>
                            Stock Status
                       </Button>
                    </div>
                </ListItem>
                <ListItem modifier="nodivider">
                    <div className="center">
                        If you are at this store right now, drag the slider to update the line numbers, or confirm the existing numbers.
                  </div>
                </ListItem>
                <ListItem modifier="nodivider">
                    <div className="center">
                        <Slider
                            defaultValue={parseInt(location.line) ? parseInt(location.line) : 0}
                            min={0}
                            max={MAX_LINE_LENGTH}
                            style={{ width: "80%", margin: "0px 15px" }}
                            valueLabelDisplay="auto"
                            valueLabelFormat={getDisplayedLineLength}
                            onChangeCommitted={function (event, value) {
                                if (event.type === "mouseup" || event.type === "touchend") {
                                    window.document.activeElement.value = value;
                                    let buttonText = '';
                                    if (location.line === value || (value === 0 && !location.line)) {
                                        buttonText = `Confirm ${getDisplayedLineLength(location.line)} ${location.line === 1 ? "person is" : "people are"} waiting in line`;
                                    } else {
                                        buttonText = `Update line length to ${getDisplayedLineLength(value)} ${value === 1 ? "person" : "people"}`;
                                    }
                                    document.getElementById(location._id).innerHTML = buttonText;
                                    updateNumber = value;
                                }
                            }}
                        />
                    </div>
                    <div className="right">
                    </div>
                </ListItem>
                <ListItem modifier="nodivider" style={{ flexWrap: 'wrap' }}>
                    <div className="center">
                        <Button id={location._id} onClick={
                            function (event) {
                                setLoadingCardList({
                                    ...loadingCardList,  //take existing key-value pairs and use them in our new state,
                                    [location._id]: true   //define new key-value pair with new uuid and [].
                                })
                                var loc = Locations.findOne({
                                    _id: location._id
                                })
                                var options = {
                                    enableHighAccuracy: true,
                                    timeout: 10000,
                                    maximumAge: 300000
                                };
                                navigator.geolocation.getCurrentPosition((position) => {
                                    //client side distance check
                                    var distanceInMeter = distance(position.coords.latitude, position.coords.longitude, loc.coordinates[1], loc.coordinates[0], "K") * 1000
                                    if (distanceInMeter > 100) {
                                        history.push("/editLine?id=" + location._id + "&lineSize=" + updateNumber, { location: location })
                                        return
                                    }
                                    Meteor.call('locations.updatelinesize', location._id, updateNumber, function (err, result) {
                                        if (err) {
                                            toast("Some error happened, Please try again later!")
                                            console.log(err)
                                            setLoadingCardList({
                                                ...loadingCardList,  //take existing key-value pairs and use them in our new state,
                                                [location._id]: false   //define new key-value pair with new uuid and [].
                                            })
                                            // history.push("/editLine?id=" + location._id + "&lineSize=" + updateNumber, { location: location })
                                            return
                                        }
                                        // setLoading(false)
                                        alert("The store has been updated, thank you!")
                                        history.go(0)
                                    });
                                }, (err) => {
                                    console.log(err)
                                    toast("Some error happened, Please try again later!")
                                    setLoadingCardList({
                                        ...loadingCardList,  //take existing key-value pairs and use them in our new state,
                                        [location._id]: false   //define new key-value pair with new uuid and [].
                                    })
                                }, options)
                            }
                        }>
                            Confirm {getDisplayedLineLength(location.line)} {location.line === 1 ? "person is" : "people are"} waiting in line
                </Button>
                    </div>
                    <div className="right">
                        <FacebookShareButton
                            url={"https://howlongistheline.org"}
                            quote={"There " + (location.line === 1 ? "was " : "were ") + getDisplayedLineLength(location.line) + " people waiting in line at " + location.name.trim() + " (" + location.address.trim() + ") " + moment(location.lastUpdate).fromNow()}
                            hashtag="#howlongistheline"
                        >
                            <FacebookIcon size={32} round />
                        </FacebookShareButton>
                        <TwitterShareButton
                            url={"https://howlongistheline.org"}
                            title={"There " + (location.line === 1 ? "was " : "were ") + getDisplayedLineLength(location.line) + " people waiting in line at " + location.name.trim() + " (" + location.address.trim() + ") " + moment(location.lastUpdate).fromNow()}
                        >
                            <TwitterIcon size={32} round />
                        </TwitterShareButton>

                    </div>
                </ListItem>
                {loadingCardList[location._id] ? <> <ProgressBar indeterminate /> Updating</> : <></>}
            </Card>
        )
    }

    return (
        <MainLayout>
            <div className="search-container" style={{ position: "sticky", top: 0, zIndex: 1000, background: "#fff" }}>
                <ListItem>
                    <SearchInput style={{ width: "100%", backgroundColor: "#d9f4ff", color: "black" }} placeholder="Find stores near you." onChange={(e) => {
                        setSearch(e.target.value)
                    }} />
                </ListItem>
            </div>
            <div className="border-top" style={{ marginBottom: 55 }}>
                <Card class="isa_info">
                    <i className="fas fa-info-circle" /> If something doesn't work properly, check back a few days later and it will probably be fixed.
                  Go <a href="https://github.com/howlongistheline/howlongistheline.org/issues">here</a> to see what the community behind this is currently working on.
                </Card>
                <ListTitle>
                    Stores Near You
          </ListTitle>
                {renderList()}
            </div>
            <Button modifier="large--cta" style={{ position: "fixed", bottom: 0, zIndex: 1000, minHeight: 50 }}
                // type="submit"
                onClick={() => { history.push('/addLine') }}>
                Missing store? Add it now!
                  <Icon style={{ marginLeft: 10 }} icon='fa-plus' />
            </Button>
            <ActionSheet isCancelable isOpen={isOpen}
            onCancel={()=>{setIsOpen(false)}}
            >
             <ActionSheetButton onClick={()=>{history.push('/duplicated?id=' + reportId)}}> Report Duplicated</ActionSheetButton>
             <ActionSheetButton onClick={()=>{history.push('/editLocation?id=' + reportId)}}> Report Wrong Location</ActionSheetButton>
             <ActionSheetButton onClick={()=>{setIsOpen(false)}}>Cancel</ActionSheetButton>
            </ActionSheet>
        </MainLayout>
    )
}
Example #23
Source File: SignUpForm.js    From wedding-website with MIT License 4 votes vote down vote up
function SignUpForm({ history }) {
    const { dispatch } = useContext(Store)
    const [cookies] = useCookies(["language"])

    const submitForm = (values, actions) => {
        const { setSubmitting, setStatus } = actions
        signUp(values, setSubmitting, setStatus, history, dispatch)
    }

    const {
        Header,
        namePlaceholder,
        emailPlaceholder,
        EmailHelp,
        passwordPlaceholder,
        SubmitButton,
        SubmitButtonLoading,
        HaveAccountPrompt,
    } = signUpForm[selectLanguage(cookies)]

    return (
        <Formik
            validationSchema={schema}
            initialValues={{
                name: "",
                email: "",
                password: "",
            }}
            onSubmit={submitForm}
        >
            {({
                handleSubmit,
                handleChange,
                handleBlur,
                values,
                touched,
                isSubmitting,
                errors,
                status,
            }) => (
                <Form
                    noValidate
                    onSubmit={handleSubmit}
                    className={styles.form}
                >
                    <div className="text-center">
                        <h4 className="text-muted">
                            <Header />
                        </h4>
                    </div>
                    <Form.Group controlId="controlIdName">
                        <Form.Control
                            name="name"
                            placeholder={namePlaceholder}
                            value={values.name}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={touched.name && errors.name}
                        />
                        <Form.Control.Feedback type="invalid">
                            {errors.name}
                        </Form.Control.Feedback>
                    </Form.Group>
                    <Form.Group controlId="controlIdEmail">
                        <Form.Control
                            name="email"
                            type="email"
                            placeholder={emailPlaceholder}
                            value={values.email}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={touched.email && errors.email}
                        />
                        <Form.Text className="text-muted">
                            <EmailHelp />
                        </Form.Text>
                        <Form.Control.Feedback type="invalid">
                            {errors.email}
                        </Form.Control.Feedback>
                    </Form.Group>
                    <Form.Group controlId="controlIdPassword">
                        <Form.Control
                            name="password"
                            type="password"
                            placeholder={passwordPlaceholder}
                            value={values.password}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={touched.password && errors.password}
                        />
                        <Form.Control.Feedback type="invalid">
                            {errors.password}
                        </Form.Control.Feedback>
                    </Form.Group>
                    <Button
                        variant="primary"
                        type="submit"
                        size="lg"
                        disabled={isSubmitting}
                        block
                    >
                        {isSubmitting ? (
                            <SubmitButtonLoading />
                        ) : (
                            <SubmitButton />
                        )}
                    </Button>
                    {status && (
                        <Alert variant="danger" className="mt-4">
                            {status}
                        </Alert>
                    )}
                    <div className={styles.links}>
                        <p>
                            <HaveAccountPrompt />
                        </p>
                    </div>
                </Form>
            )}
        </Formik>
    )
}
Example #24
Source File: SignInForm.js    From wedding-website with MIT License 4 votes vote down vote up
function SignInForm({ history }) {
    const { state, dispatch } = useContext(Store)
    const [cookies] = useCookies(["language"])

    const {
        app: {
            user: { email },
        },
    } = state

    const {
        Header,
        SubmitButton,
        SubmitButtonLoading,
        NoAccountPrompt,
        emailPlaceholder,
        passwordPlaceholder,
    } = signInForm[selectLanguage(cookies)]

    const submitForm = (values, actions) => {
        const { setSubmitting, setStatus } = actions
        signIn(values, setSubmitting, setStatus, history, dispatch)
    }

    return (
        <Formik
            validationSchema={schema}
            initialValues={{
                email: email || "",
                password: "",
            }}
            onSubmit={submitForm}
        >
            {({
                handleSubmit,
                handleChange,
                handleBlur,
                values,
                touched,
                isSubmitting,
                errors,
                status,
            }) => (
                <Form
                    noValidate
                    onSubmit={handleSubmit}
                    className={styles.form}
                >
                    <div className="text-center">
                        <h4 className="text-muted">
                            <Header />
                        </h4>
                    </div>
                    <Form.Group controlId="controlIdEmail">
                        <Form.Control
                            name="email"
                            type="email"
                            placeholder={emailPlaceholder}
                            value={values.email}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={touched.email && errors.email}
                        />
                        <Form.Control.Feedback type="invalid">
                            {errors.email}
                        </Form.Control.Feedback>
                    </Form.Group>
                    <Form.Group controlId="controlIdPassword">
                        <Form.Control
                            name="password"
                            type="password"
                            placeholder={passwordPlaceholder}
                            value={values.password}
                            onChange={handleChange}
                            onBlur={handleBlur}
                            isInvalid={touched.password && errors.password}
                        />
                        <Form.Control.Feedback type="invalid">
                            {errors.password}
                        </Form.Control.Feedback>
                    </Form.Group>
                    <Button
                        variant="primary"
                        type="submit"
                        size="lg"
                        disabled={isSubmitting}
                        block
                    >
                        {isSubmitting ? (
                            <SubmitButtonLoading />
                        ) : (
                            <SubmitButton />
                        )}
                    </Button>
                    {status && (
                        <Alert variant="danger" className="mt-4">
                            {status}
                        </Alert>
                    )}
                    <div className={styles.links}>
                        <p>
                            <NoAccountPrompt />
                        </p>
                    </div>
                </Form>
            )}
        </Formik>
    )
}
Example #25
Source File: Navigation.js    From wedding-website with MIT License 4 votes vote down vote up
function Navigation({ history }) {
    const [cookies, setCookie] = useCookies(["language"])
    const { state, dispatch } = useContext(Store)

    const {
        app: {
            user: { name, isAuthenticated, email },
        },
    } = state

    const handleSelectLanguage = lang =>
        setCookie("language", lang, { path: "/" })

    const handleSignOut = () => signOut(dispatch)

    const languageCodes = {
        [LANGUAGE.CAT]: "ES-CT",
        [LANGUAGE.EN]: "US",
    }

    const {
        schedule: ScheduleNavText,
        travel: TravelNavText,
        thingsToDo: ThingsToDoNavText,
        faq: FAQNavText,
        registry: RegistryNavText,
        rsvp: RSVPNavText,
        signOut: SignOutText,
        signIn: SignInText,
        manageRsvp: ManageRSVPText,
    } = navigation[selectLanguage(cookies)]

    return (
        <Navbar
            variant="dark"
            expand="lg"
            sticky="top"
            className={styles.navigation}
        >
            <RouterNavLink
                to="/"
                className={classNames("navbar-brand", styles.brand)}
            >
                S & L
            </RouterNavLink>
            <Navbar.Toggle />
            <Navbar.Collapse>
                <Nav>
                    <RouterNavLink
                        to="/schedule"
                        className="nav-link"
                        role="button"
                    >
                        <ScheduleNavText />
                    </RouterNavLink>
                    <RouterNavLink
                        to="/travel"
                        className="nav-link"
                        role="button"
                    >
                        <TravelNavText />
                    </RouterNavLink>
                    <RouterNavLink
                        to="/things-to-do"
                        className="nav-link"
                        role="button"
                    >
                        <ThingsToDoNavText />
                    </RouterNavLink>
                    <RouterNavLink to="/faq" className="nav-link" role="button">
                        <FAQNavText />
                    </RouterNavLink>
                    <RouterNavLink
                        to="/registry"
                        className="nav-link"
                        role="button"
                    >
                        <RegistryNavText />
                    </RouterNavLink>
                    <RouterNavLink
                        to="/rsvp"
                        className="nav-link"
                        role="button"
                    >
                        <RSVPNavText />
                    </RouterNavLink>
                </Nav>
                <Nav className="ml-auto">
                    {isAuthenticated ? (
                        <Dropdown as={NavItem}>
                            <Dropdown.Toggle as={NavLink}>
                                {name}
                            </Dropdown.Toggle>
                            <Dropdown.Menu alignRight>
                                <Dropdown.Item className={styles.email}>
                                    <strong>{email}</strong>
                                </Dropdown.Item>
                                <Dropdown.Item onSelect={handleSignOut}>
                                    <SignOutText />
                                </Dropdown.Item>
                                <Dropdown.Item
                                    onSelect={() => history.push("/rsvp")}
                                >
                                    <ManageRSVPText />
                                </Dropdown.Item>
                            </Dropdown.Menu>
                        </Dropdown>
                    ) : (
                        <RouterNavLink
                            to="/auth"
                            className="nav-link"
                            role="button"
                        >
                            <SignInText />
                        </RouterNavLink>
                    )}
                    <Dropdown as={NavItem}>
                        <Dropdown.Toggle as={NavLink}>
                            <ReactCountryFlag
                                countryCode={
                                    languageCodes[selectLanguage(cookies)]
                                }
                                svg
                            />{" "}
                            {selectLanguage(cookies)}
                        </Dropdown.Toggle>
                        <Dropdown.Menu alignRight>
                            <Dropdown.Item
                                eventKey={LANGUAGE.EN}
                                onSelect={handleSelectLanguage}
                            >
                                <ReactCountryFlag countryCode="US" svg />{" "}
                                {LANGUAGE.EN}
                            </Dropdown.Item>
                            <Dropdown.Item
                                eventKey={LANGUAGE.CAT}
                                onSelect={handleSelectLanguage}
                            >
                                <ReactCountryFlag countryCode="ES-CT" svg />{" "}
                                {LANGUAGE.CAT}
                            </Dropdown.Item>
                        </Dropdown.Menu>
                    </Dropdown>
                </Nav>
            </Navbar.Collapse>
        </Navbar>
    )
}
Example #26
Source File: index.js    From eKYC with GNU General Public License v3.0 4 votes vote down vote up
Client = () => {

    const history = useHistory();
    const [cookies, setCookie, removeCookie] = useCookies();

    const [clientData, setClientData] = useState([]);
    const [approvedFiList, setApprovedFiList] = useState([]);
    const [fiIdApprove, setFiIdApprove] = useState('');
    const [approvedMsg, setApprovedMsg] = useState('');
    const [isLoadingApprove, setIsLoadingApprove] = useState(false);
    const [fiIdRemove, setFiIdRemove] = useState('');
    const [removedMsg, setRemovedMsg] = useState('');
    const [isLoadingRemove, setIsLoadingRemove] = useState(false);

    function handleChooseFiApprove(e) {
        setFiIdApprove(e.target.value.toUpperCase());
    };

    function handleChooseFiRemove(e) {
        setFiIdRemove(e.target.value.toUpperCase());
    };

    useEffect(() => {
        try {
            axios.all([
                api.get('/client/getClientData'),
                api.get('/client/getApprovedFis')
            ])
                .then(axios.spread(
                    (clientData, approvedFis) => {
                        if (clientData.status === 200 && approvedFis.status === 200) {
                            clientData = clientData.data.clientData;
                            approvedFis = approvedFis.data.approvedFis;
                            setUserData(clientData, setClientData);
                            setApprovedFiList(approvedFis);
                        } else {
                            console.log('Oopps... something wrong, status code ' + clientData.status);
                            return function cleanup() { }
                        }
                    }))
                .catch((err) => {
                    console.log('Oopps... something wrong');
                    console.log(err);
                    return function cleanup() { }
                });
        } catch (error) {
            console.log('Oopps... something wrong');
            console.log(error);
            return function cleanup() { }
        }
    }, []);

    useEffect(() => {
        if (isLoadingApprove) {
            try {
                api
                    .post('/client/approve', qs.stringify({ fiId: fiIdApprove }))
                    .then(res => {
                        if (res.status === 200) {
                            setApprovedMsg(res.data.message);
                            const timer = setTimeout(() => {
                                setApprovedMsg('');
                            }, 5000);
                            setApprovedFiList((approvedFiList) => Array.from(new Set([...approvedFiList, fiIdApprove])));
                            return () => clearTimeout(timer);
                        } else {
                            console.log('Oopps... something wrong, status code ' + res.status);
                            return function cleanup() { }
                        }
                    })
                    .catch((err) => {
                        console.log('Oopps... something wrong1');
                        console.log(err);
                        return function cleanup() { }
                    })
                    .finally(() => {
                        setIsLoadingApprove(false);
                        setFiIdApprove('');
                    });
            } catch (error) {
                console.log('Oopps... something wrong2');
                console.log(error);
                setIsLoadingApprove(false);
                return function cleanup() { }
            }
        }
    }, [isLoadingApprove, fiIdRemove]);

    useEffect(() => {
        if (isLoadingRemove) {
            try {
                api
                    .post('/client/remove', qs.stringify({ fiId: fiIdRemove }))
                    .then(res => {
                        if (res.status === 200) {
                            setRemovedMsg(res.data.message);
                            const timer = setTimeout(() => {
                                setRemovedMsg('');
                            }, 5000);
                            setApprovedFiList((approvedFiList) => approvedFiList.filter(item => item !== fiIdRemove));
                            return () => clearTimeout(timer);
                        } else if (res.status === 202) {
                            setRemovedMsg(res.data.message);
                            const timer = setTimeout(() => {
                                setRemovedMsg('');
                            }, 5000);
                            return () => clearTimeout(timer);
                        } else {
                            console.log('Oopps... something wrong, status code ' + res.status);
                            return function cleanup() { }
                        }
                    })
                    .catch((err) => {
                        console.log('Oopps... something wrong1');
                        console.log(err);
                        return function cleanup() { }
                    })
                    .finally(() => {
                        setIsLoadingRemove(false);
                        setFiIdRemove('');
                    });
            } catch (error) {
                console.log('Oopps... something wrong2');
                console.log(error);
                setIsLoadingRemove(false);
                return function cleanup() { }
            }
        }
    }, [isLoadingRemove, fiIdRemove]);

    const handleSubmitApprove = e => {
        e.preventDefault();

        if (approvedFiList.includes(fiIdApprove)) {
            setApprovedMsg(`${fiIdApprove} already approved`);
            setTimeout(() => {
                setApprovedMsg('');
            }, 5000);
            setFiIdApprove('');
        } else {
            setIsLoadingApprove(true);
            setApprovedMsg('');
        }
    };

    const handleSubmitRemove = e => {
        e.preventDefault();

        if (!approvedFiList.includes(fiIdRemove)) {
            setRemovedMsg(`${fiIdRemove} is not approved`);
            setTimeout(() => {
                setRemovedMsg('');
            }, 5000);
            setFiIdRemove('');
        } else {
            setIsLoadingRemove(true);
            setRemovedMsg('');
        }
    };

    function handleClickLogout() {
        removeCookie('userJWT');
        removeCookie('ledgerId');
        removeCookie('whoRegistered');
        removeCookie('orgCredentials');
        history.push('/login');
    }

    return (
        <Flex minWidth={380}>
            <Box mx={'auto'} width={[1, 10 / 12]}>
                <Flex px={2} mx={'auto'} justifyContent='space-between'>
                    <Box my={'auto'}>
                        <Heading as={'h1'} color='primary'>eKYC</Heading>
                    </Box>
                    <Box my={'auto'}>
                        <Button onClick={handleClickLogout}>Logout</Button>
                    </Box>
                </Flex>
                <Card>
                    <Heading as={'h2'}>Client data</Heading>
                    <UserData userData={clientData} />
                </Card>
                <Card mt={20}>
                    <Flex my={1}>
                        <Box ml={10} my={1}>
                            {approvedFiList.length > 0 ?
                                <Heading as={'h3'} my={'auto'}>Your approved financial institutions:</Heading>
                                :
                                <Heading as={'h3'} my={'auto'}>You have no approved financial institutions</Heading>
                            }
                        </Box>
                        <Box ml={10} my={1}>
                            {approvedFiList.join(', ')}
                        </Box>
                    </Flex>
                </Card>
                <Card mt={20}>
                    <Heading as={'h2'}>Approve financial institution</Heading>
                    <Form onSubmit={handleSubmitApprove}>
                        <Flex mx={-3}>
                            <Box width={1} px={3}>
                                <Field label="Financial institution ID" width={1}>
                                    <Form.Input
                                        type="text"
                                        required
                                        onChange={handleChooseFiApprove}
                                        value={fiIdApprove}
                                        width={1}
                                    />
                                </Field>
                            </Box>
                        </Flex>
                        <Flex mx={-3} alignItems={'center'}>
                            <Box px={3}>
                                <Button type="submit" disabled={isLoadingApprove}>
                                    {isLoadingApprove ? <Loader color="white" /> : <p>Approve</p>}
                                </Button>
                            </Box>
                            {approvedMsg &&
                                <Box px={3}>
                                    <Text>{approvedMsg}</Text>
                                </Box>
                            }
                        </Flex>
                    </Form>
                </Card>
                <Card mt={20}>
                    <Heading as={'h2'}>Remove financial institution approval</Heading>
                    <Form onSubmit={handleSubmitRemove}>
                        <Flex mx={-3}>
                            <Box width={1} px={3}>
                                <Field label="Financial institution ID" width={1}>
                                    <Form.Input
                                        type="text"
                                        required
                                        onChange={handleChooseFiRemove}
                                        value={fiIdRemove}
                                        width={1}
                                    />
                                </Field>
                            </Box>
                        </Flex>
                        <Flex mx={-3} alignItems={'center'}>
                            <Box px={3}>
                                <Button type="submit" disabled={isLoadingRemove}>
                                    {isLoadingRemove ? <Loader color="white" /> : <p>Remove</p>}
                                </Button>
                            </Box>
                            {removedMsg &&
                                <Box px={3}>
                                    <Text>{removedMsg}</Text>
                                </Box>
                            }
                        </Flex>
                    </Form>
                </Card>
            </Box>
        </Flex>
    );
}
Example #27
Source File: Index_DEPRECATED.jsx    From howlongistheline.org with Mozilla Public License 2.0 4 votes vote down vote up
function Index({ history }) {
    const [loc, setLoc] = useCookies(['location']);
    const [nearby, setNearby] = useState();
    const [AllLocations, setAllLocations] = useState([])
    const [search, setSearch] = useState("");
    const [line, setLine] = useState();
    const [loading, setLoading] = useState(false);
    const [denied, setDenied] = useState(false);

    function isOpening(location){
        if(!location.opening || !location.closing){
            return true
        }
        var d = new Date();
        var now;
        var open;
        var close;
        if(d.getUTCMinutes() < 10){
            now = d.getUTCHours() + ".0" + d.getUTCMinutes();
        }
        else{
            now = d.getUTCHours() + "." + d.getUTCMinutes();
        }
        if(location.opening[1] < 10){
            open = location.opening[0]+".0"+location.opening[1]
        }else
        {
            open = location.opening[0]+"."+location.opening[1]
        }
        if(location.closing[1]< 10){
            close = location.closing[0]+".0"+location.closing[1]
        }else{
            close = location.closing[0]+"."+location.closing[1]
        }

        if(close > open){
            if(now > open && now < close)
            {
                return true
            }
            else
            {
                return false
            }
        }
        else{
            if(close > now || (now > open && 24 > now)){
                return true
            }else{
                return false
            }
        }
    }

    function compare(a, b) {
        if (distance(a.coordinates[1], a.coordinates[0], loc.location.latitude, loc.location.longitude, "K") < distance(b.coordinates[1], b.coordinates[0], loc.location.latitude, loc.location.longitude, "K"))
            return -1;
        if (distance(a.coordinates[1], a.coordinates[0], loc.location.latitude, loc.location.longitude, "K") > distance(b.coordinates[1], b.coordinates[0], loc.location.latitude, loc.location.longitude, "K"))
            return 1;
        return 0;
    }

    function distance(lat1, lon1, lat2, lon2, unit) {
        if ((lat1 == lat2) && (lon1 == lon2)) {
            return 0;
        }
        else {
            var radlat1 = Math.PI * lat1 / 180;
            var radlat2 = Math.PI * lat2 / 180;
            var theta = lon1 - lon2;
            var radtheta = Math.PI * theta / 180;
            var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
            if (dist > 1) {
                dist = 1;
            }
            dist = Math.acos(dist);
            dist = dist * 180 / Math.PI;
            dist = dist * 60 * 1.1515;
            if (unit == "K") { dist = dist * 1.609344 }
            if (unit == "N") { dist = dist * 0.8684 }
            return dist;
        }
    }

    useEffect(() => {
        if (loc.location != undefined) {
            if ((new Date().getTime() - new Date(loc.location.time).getTime()) / 1000 < 300) {
                // getNearby(loc.location.longitude, loc.location.latitude)
            }
            else {
                getLocation()
            }
        }
        else {
            getLocation()
        }
        return () => {
        }
    }, [])

    function getLocation() {
        navigator.geolocation.getCurrentPosition((position) => {
            setLoc('location', { longitude: position.coords.longitude, latitude: position.coords.latitude, time: new Date() }, { path: '/' });
            getNearby(position.coords.longitude, position.coords.latitude)
        }, (err) => {
            setDenied(true)
            toast("Can't get current location, please turn on browser's geolocation function and refresh, or try a different browser")
            console.warn(`ERROR(${err.code}): ${err.message}`);
        });
    }


    function getNearby(long, lat) {
        Meteor.call('locations.findnearby', long, lat, (err, result) => {
            setNearby(result)
        })
    }


    useEffect(() => {
        let isCancelled = false;
        try {
            if (!isCancelled) {
                Tracker.autorun(function () {
                    if (!isCancelled) {
                        if (search == "") {
                            setAllLocations(Locations.find({}, { sort: { lastUpdate: -1 }, limit: 500 }).fetch())
                        }
                        else {
                            let cursor = LocationsIndex.search(search)
                            setAllLocations(cursor.fetch())
                        }
                    }
                })
            }
        } catch (e) {
            if (!isCancelled) {
                throw e;
            }
        }
        return function cleanup() {
            isCancelled = true;
        }
    }, [search])

    function renderCard(location) {
      var lineupdate = 0;
      var Indicator = "green"
      switch(true){
        case (location.line == undefined):
            Indicator = "green"
            break
        case (location.line <= 20 && location.line >= 0 ):
            Indicator = "green"
            break
        case (location.line <= 35 && location.line > 20 ):
            Indicator = "orange"
            break
        case (location.line > 35 ):
            Indicator = "red"
            break
      }
        return (
            <Card key={location._id} style={{backgroundColor: isOpening(location)? "" : "grey"}}>
                <ListItem modifier="nodivider">
                    {location.name}
                </ListItem>
                <ListItem modifier="nodivider">
                    {location.address}
                    {/*<div className="right">
                         }<Button
                        onClick={() => {
                            history.push('/shopDetails?id=' + location._id)
                        }}
                    >More Details</Button>
                    </div> */}
                </ListItem>
                <ListItem modifier="nodivider">
                    <div className="center" style={{color:Indicator}}>
                        There {location.line === 1 ? "was" : "were"} {location.line ? location.line : 0} {location.line === 1 ? "person" : "people"} in line {moment(location.lastUpdate).fromNow()}.
                    </div>
                    <div className="right">
                        {isOpening(location) ? "": "Closed"}
                    </div>
                </ListItem>
                <ListItem modifier="nodivider">
                <div className="center">
                0
                <Range modifier="material" style={{width:"80%"}} min={0} max={50} value={parseInt(location.line) ? parseInt(location.line) : 0}
                onChange={ function(event) {
                  if (event.type == "change") {
                    navigator.geolocation.getCurrentPosition((position) => {
                        Meteor.call('locations.updatelinesize', location._id, position.coords.longitude, position.coords.latitude, event.target.value, function (err, result) {
                          console.log(event.type)
                            if (err) {
                                setLoading(false)
                                toast("Are you at this store right now?")
                                console.log(err)
                                return
                            }
                            // setLoading(false)
                            toast("Thank You!")
                            history.push('/')
                        });
                    })
                  }}}

                />
                50+
                </div>
                </ListItem>
                <ListItem modifier="nodivider">
                <div className="center">If you are at this store, drag the slider above to update the number of people waiting in line right now.</div>
                </ListItem>
            </Card>
        )
    }

    function statusToWord(statusCode) {
        switch (statusCode) {
            case "no":
                return <div style={{ color: "green" }}>No Lines!</div>
            case "small":
                return <div style={{ color: "orange" }}>A Wee Wait</div>
            case "long":
                return <div style={{ color: "red" }}>Busy. Stay Home.</div>
        }
    }

    function renderList() {
        if (loc.location != undefined) {
            var sorted = AllLocations.sort(compare)
            return sorted.map((location) => {
                return renderCard(location)
            })
        }
        return AllLocations.map((location) => {
            return renderCard(location)
        })
    }

    function renderNearby() {
        if (!nearby) {
            return (
                <Card>
                    <div><ProgressCircular indeterminate />Please wait, finding your current location...</div>
                </Card>
            )
        }
        return nearby.map((location) => {
            return renderCard(location)
        })
    }

    function renderLoading() {
        if(denied){
            return
        }
        if (loc.location == undefined) {
            return (<Card>
                <ProgressBar indeterminate />
                Getting your location...
            </Card>
            )
        }
        else {
            return
        }
    }


    if (search != "") {
        return (
            <MainLayout>
                <div style={{ position: "sticky", top: 0, zIndex: 1000}}>
                    <ListItem>
                        <SearchInput style={{ width: "80%", backgroundColor: "#d9f4ff", color: 'black'}} placeholder="Start typing the name of a store or locality to find things!" onChange={(e) => {
                            setSearch(e.target.value)
                        }} />
                    </ListItem>
                </div>
                <div style={{ marginBottom: 55 }}>
                    <ListTitle>
                        Results
                </ListTitle>
                    {renderList()}
                </div>
                <Button modifier="large--cta" style={{ position: "fixed", bottom: 0, zIndex: 1000, minHeight: 50 }}
                    // type="submit"
                    onClick={() => { history.push('/addLine') }}>
                    Missing store? Add it now!
                        <Icon style={{ marginLeft: 10 }} icon='fa-plus' />
                </Button>
            </MainLayout>
        )
    }


    return (
        <MainLayout>
            <div style={{ position: "sticky", top: 0, zIndex: 1000 }}>
                <ListItem>
                    <SearchInput style={{ width: "80%", backgroundColor: "#d9f4ff", color: "black"}} placeholder="Start typing the name of a store or locality to find things!" onChange={(e) => {
                        setSearch(e.target.value)
                    }} />
                </ListItem>
            </div>
            <div style={{ marginBottom: 55 }}>
                {renderLoading()}
                <ListTitle>
                    All Stores
            </ListTitle>
                {renderList()}
            </div>
            <Button modifier="large--cta" style={{ position: "fixed", bottom: 0, zIndex: 1000, minHeight: 50 }}
                // type="submit"
                onClick={() => { history.push('/addLine') }}>
                Missing store? Add it now!
                    <Icon style={{ marginLeft: 10 }} icon='fa-plus' />
            </Button>
        </MainLayout>
    )
}
Example #28
Source File: JoinNewsletter.js    From flotiq-blog with MIT License 4 votes vote down vote up
JoinNewsletter = ({ addMargin = false }) => {
    const [cookies, setCookie] = useCookies([COOKIE_KEY2]);
    const isBrowser = () => typeof window !== 'undefined';
    const nextWeek = () => {
        const today = new Date();
        return new Date(today.getTime() + (7 * 24 * 60 * 60 * 1000));
    };

    const dismiss = () => {
        setCookie(COOKIE_KEY2, 1, { expires: nextWeek() });
    };
    const action = 'https://flotiq.us18.list-manage.com/subscribe/post?u=5f7db102d539d8f65a3639f8d&amp;id=da58181767';
    return (
        <Row className="w-100">
            {
                (isBrowser() && cookies && !cookies[COOKIE_KEY2]) ? (
                    <Container className={addMargin ? 'pt-5 pb-5 mb-5' : ''}>
                        <div id="mc_embed_signup">
                            <form
                                action={action}
                                method="post"
                                id="mc-embedded-subscribe-form"
                                name="mc-embedded-subscribe-form"
                                className="validate"
                                target="_blank"
                                noValidate
                            >
                                <div id="mc_embed_signup_scroll" className="join-newsletter-box">
                                    <div className="join-newsletter-box-header">
                                        <h4><strong>Join our newsletter</strong></h4>
                                        <button
                                            aria-label="Close"
                                            className="join-newsletter-close-btn d-inline-block d-md-none"
                                            onClick={() => dismiss()}
                                        >
                                            <img
                                                alt="Close join newsletter box"
                                                src={Close}
                                            />
                                        </button>
                                    </div>
                                    <div className="join-newsletter-box-form">
                                        <input
                                            type="email"
                                            name="EMAIL"
                                            className="email join-newsletter-subscription"
                                            id="mce-EMAIL"
                                            placeholder="Enter your email address"
                                            required
                                        />
                                        <div style={{ position: 'absolute', left: '-5000px' }} aria-hidden="true">
                                            <input
                                                type="text"
                                                name="b_5f7db102d539d8f65a3639f8d_da58181767"
                                                tabIndex="-1"
                                            />
                                        </div>
                                        <button
                                            type="submit"
                                            name="subscribe"
                                            id="mc-embedded-subscribe"
                                            className="btn join-newsletter-subscription-button"
                                        >
                                            Subscribe
                                        </button>
                                    </div>
                                    <button
                                        aria-label="Close"
                                        className="join-newsletter-close-btn d-none d-md-inline-block"
                                        onClick={() => dismiss()}
                                    >
                                        <img
                                            alt="Close join newsletter box"
                                            src={Close}
                                        />
                                    </button>
                                </div>
                            </form>
                        </div>
                    </Container>
                ) : null
            }
        </Row>
    );
}
Example #29
Source File: AccountListener.js    From origin-dollar with MIT License 4 votes vote down vote up
AccountListener = (props) => {
  const web3react = useWeb3React()
  const { account, chainId, library, active } = web3react
  const prevAccount = usePrevious(account)
  const prevActive = usePrevious(active)
  const [contracts, setContracts] = useState(null)
  const [cookies, setCookie, removeCookie] = useCookies(['loggedIn'])
  const {
    active: userActive,
    refetchUserData,
    refetchStakingData,
  } = useStoreState(AccountStore, (s) => s)
  const durations = useStoreState(StakeStore, (s) => s.durations)
  const rates = useStoreState(StakeStore, (s) => s.rates)
  const prevRefetchStakingData = usePrevious(refetchStakingData)
  const prevRefetchUserData = usePrevious(refetchUserData)
  const AIR_DROPPED_STAKE_TYPE = 1

  const balancesQuery = useBalancesQuery(account, contracts, {
    onSuccess: (balances) => {
      AccountStore.update((s) => {
        s.balances = balances
      })
    },
  })

  const allowancesQuery = useAllowancesQuery(account, contracts, {
    onSuccess: (allowances) => {
      AccountStore.update((s) => {
        s.allowances = allowances
      })
    },
  })

  const wousdQuery = useWousdQuery(account, contracts, {
    onSuccess: (wousdValue) => {
      AccountStore.update((s) => {
        s.wousdValue = wousdValue
      })
    },
  })

  const apyQuery = useApyQuery({
    onSuccess: (apy) => {
      ContractStore.update((s) => {
        s.apy = apy
      })
    },
  })

  const historyQuery = useTransactionHistoryQuery(account)

  useEffect(() => {
    if ((prevActive && !active) || prevAccount !== account) {
      AccountStore.update((s) => {
        s.allowances = {}
        s.balances = {}
      })
      PoolStore.update((s) => {
        s.claimable_ogn = null
        s.lp_tokens = null
        s.lp_token_allowance = null
        s.staked_lp_tokens = null
        s.your_weekly_rate = null
      })
      StakeStore.update((s) => {
        s.stakes = null
        s.airDropStakeClaimed = false
      })
    }
  }, [active, prevActive, account, prevAccount])

  useEffect(() => {
    const fetchVaultThresholds = async () => {
      if (!contracts) return

      const vault = contracts.vault
      const allocateThreshold = await vault.autoAllocateThreshold()
      const rebaseThreshold = await vault.rebaseThreshold()

      ContractStore.update((s) => {
        s.vaultAllocateThreshold = allocateThreshold
        s.vaultRebaseThreshold = rebaseThreshold
      })
    }

    fetchVaultThresholds()
  }, [contracts])

  const loadData = async (contracts, { onlyStaking } = {}) => {
    if (!account) {
      return
    }
    if (!contracts.ogn.provider) {
      console.warn('Contract provider not yet set')
      return
    }
    if (!contracts) {
      console.warn('Contracts not yet loaded!')
      return
    }
    if (!isCorrectNetwork(chainId)) {
      return
    }

    const { ousd, ogn, ognStakingView } = contracts

    const loadPoolRelatedAccountData = async () => {
      if (!account) return
      if (process.env.ENABLE_LIQUIDITY_MINING !== 'true') return

      const pools = PoolStore.currentState.pools
      const initializedPools = pools.filter((pool) => pool.contract)

      if (pools.length !== initializedPools.length) {
        console.warn(
          'When loading account pool data not all pools have yet initialized'
        )
      }

      // contract needs to be populated?

      // await poolContract.userInfo(account)
      // await displayCurrency(userInfo.amount, lpContract)
      try {
        const additionalPoolData = await Promise.all(
          pools.map(async (pool) => {
            const { lpContract, contract, pool_deposits_bn } = pool
            const additionalData = {
              name: pool.name,
              coin_one: {},
              coin_two: {},
            }

            if (isDevelopment) {
              const token1Contract =
                contracts[pool.coin_one.contract_variable_name]
              const token2Contract =
                contracts[pool.coin_two.contract_variable_name]

              const [
                coin1Allowance,
                coin2Allowance,
                coin1Balance,
                coin2Balance,
              ] = await Promise.all([
                displayCurrency(
                  await token1Contract.allowance(account, lpContract.address),
                  token1Contract
                ),
                displayCurrency(
                  await token2Contract.allowance(account, lpContract.address),
                  token2Contract
                ),
                displayCurrency(
                  await token1Contract.balanceOf(account),
                  token1Contract
                ),
                displayCurrency(
                  await token2Contract.balanceOf(account),
                  token2Contract
                ),
              ])

              additionalData.coin_one.allowance = coin1Allowance
              additionalData.coin_two.allowance = coin2Allowance
              additionalData.coin_one.balance = coin1Balance
              additionalData.coin_two.balance = coin2Balance
              additionalData.coin_one.contract = token1Contract
              additionalData.coin_two.contract = token2Contract
            }

            const [
              userInfo,
              unclaimedOgn,
              lp_tokens,
              lp_token_allowance,
              rewardPerBlockBn,
              userReward,
              poolDepositsBn,
            ] = await Promise.all([
              await contract.userInfo(account),
              displayCurrency(await contract.pendingRewards(account), ogn),
              displayCurrency(await lpContract.balanceOf(account), lpContract),
              displayCurrency(
                await lpContract.allowance(account, contract.address),
                lpContract
              ),
              await contract.rewardPerBlock(),
              displayCurrency(await contract.pendingRewards(account), ogn),
              await lpContract.balanceOf(contract.address),
            ])

            const userTokensStaked = await displayCurrency(
              userInfo.amount,
              lpContract
            )

            additionalData.claimable_ogn = unclaimedOgn
            additionalData.lp_tokens = lp_tokens
            additionalData.lp_token_allowance = lp_token_allowance
            additionalData.staked_lp_tokens = userTokensStaked
            additionalData.pool_deposits = await displayCurrency(
              poolDepositsBn,
              lpContract
            )
            additionalData.reward_per_block = await displayCurrency(
              rewardPerBlockBn,
              ogn
            )

            const userTokensStakedNumber = Number(userTokensStaked)
            /* userTokensStaked / total pool deposits = the share of the pool a user owns
             * Multiplied by rewards per block times number of blocks in a week
             */
            additionalData.your_weekly_rate =
              userTokensStakedNumber === 0 || poolDepositsBn.isZero()
                ? 0
                : await displayCurrency(
                    userInfo.amount
                      /* in dev environment sometimes users can have more tokens staked than total pool token staked.
                       * that happens when user balance updates before the pool balance.
                       */
                      .div(poolDepositsBn)
                      .mul(rewardPerBlockBn)
                      .mul(BigNumber.from(6500 * 7)), // blocks in a day times 7 days in a week
                    ogn
                  )
            return additionalData
          })
        )

        const enrichedPools = PoolStore.currentState.pools.map((pool) => {
          const additionalData = additionalPoolData.filter(
            (apool) => apool.name === pool.name
          )[0]
          const merged = {
            ...pool,
            ...additionalData,
            coin_one: {
              ...pool.coin_one,
              ...additionalData.coin_one,
            },
            coin_two: {
              ...pool.coin_two,
              ...additionalData.coin_two,
            },
          }

          return merged
        })
        //console.log('Enriched pools', enrichedPools)
        PoolStore.update((s) => {
          s.pools = enrichedPools
        })
      } catch (e) {
        console.error(
          'AccountListener.js error - can not load account specific data for pools',
          e
        )
      }
    }

    const loadStakingRelatedData = async () => {
      if (!account) return

      try {
        /* OgnStakingView is used here instead of ognStaking because the first uses the jsonRpcProvider and
         * the latter the wallet one. Sometime these are not completely in sync and while the first one might
         * report a transaction already mined, the second one not yet.
         *
         * We use jsonRpcProvider to wait for transactions to be mined, so using the samne provider to fetch the
         * staking data solves the out of sync problem.
         */
        const [stakes, airDropStakeClaimed] = await Promise.all([
          ognStakingView.getAllStakes(account),
          ognStakingView.airDroppedStakeClaimed(
            account,
            AIR_DROPPED_STAKE_TYPE
          ),
        ])

        const decoratedStakes = stakes
          ? decorateContractStakeInfoWithTxHashes(stakes)
          : []

        StakeStore.update((s) => {
          s.stakes = decoratedStakes
          s.airDropStakeClaimed = airDropStakeClaimed
        })
      } catch (e) {
        console.error(
          'AccountListener.js error - can not load staking related data: ',
          e
        )
      }
    }

    const loadRebaseStatus = async () => {
      if (!account) return
      // TODO handle other contract types. We only detect Gnosis Safe as having
      // opted out here as rebaseState will always be 0 for all EOAs
      const isSafe = !!_.get(library, 'provider.safe.safeAddress', false)
      AccountStore.update((s) => {
        s.isSafe = isSafe
      })
      const rebaseOptInState = await ousd.rebaseState(account)
      AccountStore.update((s) => {
        s.rebaseOptedOut = isSafe && rebaseOptInState === 0
      })
    }

    if (onlyStaking) {
      await loadStakingRelatedData()
    } else {
      balancesQuery.refetch()
      allowancesQuery.refetch()
      wousdQuery.refetch()

      await Promise.all([
        loadRebaseStatus(),
        // TODO maybe do this if only in the LM part of the dapp since it is very heavy
        loadPoolRelatedAccountData(),
        loadStakingRelatedData(),
      ])
    }
  }

  useEffect(() => {
    if (account) {
      login(account, setCookie)
      historyQuery.refetch()
    }

    const loadLifetimeEarnings = async () => {
      if (!account) return

      const response = await fetch(
        `${
          process.env.ANALYTICS_ENDPOINT
        }/api/v1/address/${account.toLowerCase()}/yield`
      )

      if (response !== undefined && response.ok) {
        const lifetimeYield = (await response.json()).lifetime_yield
        AccountStore.update((s) => {
          s.lifetimeYield = lifetimeYield
        })
      }
    }

    const setupContractsAndLoad = async () => {
      /* If we have a web3 provider present and is signed into the allowed network:
       * - NODE_ENV === production -> mainnet
       * - NODE_ENV === development -> localhost, forknet
       * then we use that chainId to setup contracts.
       *
       * In other case we still want to have read only capability of the contracts with a general provider
       * so we can fetch `getAPR` from Vault for example to use on marketing pages even when the user is not
       * logged in with a web3 provider.
       *
       */
      let usedChainId, usedLibrary
      if (chainId && isCorrectNetwork(chainId)) {
        usedChainId = chainId
        usedLibrary = library
      } else {
        usedChainId = parseInt(process.env.ETHEREUM_RPC_CHAIN_ID)
        usedLibrary = null
      }

      window.fetchId = window.fetchId ? window.fetchId : 0
      window.fetchId += 1
      apyQuery.refetch()

      const contracts = await setupContracts(
        account,
        usedLibrary,
        usedChainId,
        window.fetchId
      )
      setContracts(contracts)

      setTimeout(() => {
        loadData(contracts)
      }, 1)
    }

    setupContractsAndLoad()
    loadLifetimeEarnings()
  }, [account, chainId])

  useEffect(() => {
    // trigger a force refetch user data when the flag is set by a user
    if (
      (contracts && isCorrectNetwork(chainId),
      refetchUserData && !prevRefetchUserData)
    ) {
      loadData(contracts)
    }
    AccountStore.update((s) => {
      s.refetchUserData = false
    })
  }, [userActive, contracts, refetchUserData, prevRefetchUserData])

  useEffect(() => {
    // trigger a force refetch user data when the flag is set by a user
    if (
      (contracts && isCorrectNetwork(chainId),
      refetchStakingData && !prevRefetchStakingData)
    ) {
      loadData(contracts, { onlyStaking: true })
    }
    AccountStore.update((s) => {
      s.refetchStakingData = false
    })
  }, [userActive, contracts, refetchStakingData, prevRefetchStakingData])

  useEffect(() => {
    let balancesInterval
    if (contracts && userActive === 'active' && isCorrectNetwork(chainId)) {
      loadData(contracts)

      balancesInterval = setInterval(() => {
        loadData(contracts)
      }, 7000)
    }

    return () => {
      if (balancesInterval) {
        clearInterval(balancesInterval)
      }
    }
  }, [userActive, contracts])

  return ''
}