@apollo/client#useApolloClient JavaScript Examples

The following examples show how to use @apollo/client#useApolloClient. 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: signout.js    From next-ecommerce with MIT License 6 votes vote down vote up
function SignOut() {
  const client = useApolloClient();
  const router = useRouter();
  const [signOut] = useMutation(SignOutMutation);

  useEffect(() => {
    signOut().then(() => {
      client.resetStore().then(() => {
        router.push('/user/login');
      });
    });
  }, [signOut, router, client]);

  return <p>Signing out...</p>;
}
Example #2
Source File: index.js    From realworld with MIT License 6 votes vote down vote up
export default function LogoutPage() {
  const client = useApolloClient();
  useEffect(() => {
    document.cookie = cookie.serialize('authorization', '', {
      maxAge: -1,
      path: '/',
      sameSite: 'lax',
      secure: process.env.NODE_ENV === 'production',
    });

    client.resetStore().then(() => Router.push('/'));
  }, [client]);

  return null;
}
Example #3
Source File: errorHandling.js    From generator-webapp-rocket with MIT License 6 votes vote down vote up
export function useClientQueryWithErrorHandling() {
  const client = useApolloClient();
  const showError = useError();
  return async (query, props) => {
    try {
      return await client.query({
        query,
        ...props
      })
    } catch (error) {
      showError(error);
      return { loading: false, error };
    }
  }
}
Example #4
Source File: hooks.js    From malware-detection-frontend with Apache License 2.0 5 votes vote down vote up
useFetchSystems = ({
    query,
    onComplete,
    onError
}) => {
    const client = useApolloClient();

    return (limit, offset, requestVariables = {}) =>
        client
        .query({
            query,
            fetchResults: true,
            fetchPolicy: 'no-cache',
            variables: {
                limit,
                offset,
                ...requestVariables
            }
        })
        .then(({ data }) => {
            const entities = data?.hostsList || [];
            const result = {
                entities,
                meta: {
                    ...(requestVariables.tags && { tags: requestVariables.tags }),
                    totalCount: data?.hosts?.totalCount || 0
                }
            };

            onComplete?.(result);
            return result;
        })
        .catch((error) => {
            if (onError) {
                onError(error);
                return { entities: [], meta: { totalCount: 0 } };
            } else {
                throw error;
            }
        });
}
Example #5
Source File: HospitalPage.js    From bedav with GNU General Public License v3.0 5 votes vote down vote up
function HospitalPage(props) {
  let { hospitalId } = useParams();
  const client = useApolloClient();
  hospitalId = decodeURIComponent(hospitalId);

  useEffect(() => {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
  });

  let cachedHospital = client.readFragment({
    id: `Hospital:${hospitalId}`,
    fragment: HospitalInfoFragment,
  });

  const [hospital, setHospital] = useState(cachedHospital);
  const [getHospital, { data, loading }] = useLazyQuery(PageQuery, {
    variables: {
      hospitalId: hospitalId,
    },
  });

  if (data && data.hospital && !hospital) {
    setHospital(data.hospital);
  }

  if (hospital) {
    document.title = "Bedav - " + hospital.name;
  } else if (loading) {
    return <Spinner />;
  } else if (hospital === null) {
    getHospital({
      variables: {
        hospitalId,
      },
    });

    return <Spinner />;
  }

  return (
    <>
      <MainContainer>
        <BedInfoSection hospital={hospital} />
        <HospitalInfoSection hospital={hospital} />
      </MainContainer>
    </>
  );
}
Example #6
Source File: comments.js    From stacker.news with MIT License 5 votes vote down vote up
export default function Comments ({ parentId, comments, ...props }) {
  const client = useApolloClient()
  useEffect(() => {
    const hash = window.location.hash
    if (hash) {
      document.querySelector(hash).scrollIntoView({ behavior: 'smooth' })
    }
  }, [])
  const [getComments, { loading }] = useLazyQuery(COMMENTS_QUERY, {
    fetchPolicy: 'network-only',
    onCompleted: data => {
      client.writeFragment({
        id: `Item:${parentId}`,
        fragment: gql`
          ${COMMENTS}
          fragment Comments on Item {
            comments {
              ...CommentsRecursive
            }
          }
        `,
        fragmentName: 'Comments',
        data: {
          comments: data.comments
        }
      })
    }
  })

  return (
    <>
      {comments.length ? <CommentsHeader handleSort={sort => getComments({ variables: { id: parentId, sort } })} /> : null}
      {loading
        ? <CommentsSkeleton />
        : comments.map(item => (
          <Comment depth={1} key={item.id} item={item} {...props} />
        ))}
    </>
  )
}
Example #7
Source File: discussion-form.js    From stacker.news with MIT License 5 votes vote down vote up
export function DiscussionForm ({
  item, editThreshold, titleLabel = 'title',
  textLabel = 'text', buttonText = 'post',
  adv, handleSubmit
}) {
  const router = useRouter()
  const client = useApolloClient()
  const [upsertDiscussion] = useMutation(
    gql`
      mutation upsertDiscussion($id: ID, $title: String!, $text: String, $boost: Int, $forward: String) {
        upsertDiscussion(id: $id, title: $title, text: $text, boost: $boost, forward: $forward) {
          id
        }
      }`
  )

  const DiscussionSchema = Yup.object({
    title: Yup.string().required('required').trim(),
    ...AdvPostSchema(client)
  })

  return (
    <Form
      initial={{
        title: item?.title || '',
        text: item?.text || '',
        ...AdvPostInitial
      }}
      schema={DiscussionSchema}
      onSubmit={handleSubmit || (async ({ boost, ...values }) => {
        const { error } = await upsertDiscussion({
          variables: { id: item?.id, boost: Number(boost), ...values }
        })
        if (error) {
          throw new Error({ message: error.toString() })
        }

        if (item) {
          await router.push(`/items/${item.id}`)
        } else {
          await router.push('/recent')
        }
      })}
      storageKeyPrefix={item ? undefined : 'discussion'}
    >
      <Input
        label={titleLabel}
        name='title'
        required
        autoFocus
      />
      <MarkdownInput
        label={<>{textLabel} <small className='text-muted ml-2'>optional</small></>}
        name='text'
        as={TextareaAutosize}
        minRows={6}
        hint={editThreshold
          ? <div className='text-muted font-weight-bold'><Countdown date={editThreshold} /></div>
          : null}
      />
      {!item && adv && <AdvPostForm />}
      <ActionTooltip>
        <SubmitButton variant='secondary' className='mt-3'>{item ? 'save' : buttonText}</SubmitButton>
      </ActionTooltip>
    </Form>
  )
}
Example #8
Source File: login.js    From next-ecommerce with MIT License 4 votes vote down vote up
export default function Login() {
  const client = useApolloClient();
  const [signIn] = useMutation(SIGN_IN);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [msgError, setMsgError] = useState('');

  const router = useRouter();

  async function handleSubmit(e) {
    e.preventDefault();

    try {
      await client.resetStore();
      const { data } = await signIn({
        variables: {
          email: email.trim(),
          password: password.trim(),
        },
      });
      if (data.signIn.user) {
        await router.push('/');
      }
    } catch (error) {
      setMsgError(getErrorMessage(error));
    }
  }

  return (
    <PageContainer title="Quantum E-commerce - Login">
      <FormContainer>
        <form onSubmit={handleSubmit}>
          <h3 className="formTitle">login</h3>

          {msgError && <AlertError message={msgError} />}

          <InputContainer>
            <Input
              type="email"
              name="email"
              placeholder="Email"
              onChange={(value) => setEmail(value)}
              value={email}
            />
            <Input
              type="password"
              name="password"
              placeholder="Password"
              onChange={(value) => setPassword(value)}
              value={password}
            />

            <Button type="submit" title="Login" />
          </InputContainer>
        </form>

        <Link href="/user/signup">
          <a className="switchForm">I do not have a account</a>
        </Link>
        <Link href="/user/resetpassword">
          <a className="switchForm">I forgot my password</a>
        </Link>
      </FormContainer>

      <style jsx>{`
        form {
          width: 100%;
          align-items: center;
        }
        form .formTitle {
          text-align: center;
          font-size: 38px;
          font-weight: 1000;
          letter-spacing: 1.65px;
          color: #b2b2b2;
          text-transform: uppercase;
          margin-bottom: 84px;
        }
        .switchForm {
          color: #b2b2b2;
          margin-top: 12px;
          font-weight: 500;
        }
      `}</style>
    </PageContainer>
  );
}
Example #9
Source File: NavBar.js    From stack-underflow with MIT License 4 votes vote down vote up
NavBar = () => {
  const { user, logoutUser } = useAuthContext();
  const [searchOpen, setSearchOpen] = useState(false);
  const client = useApolloClient();
  const classes = useNavStyles();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('xs'));

  useEffect(() => {
    if (!isMobile && searchOpen) {
      setSearchOpen(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isMobile]);

  const handleLogout = () => {
    logoutUser();
    client.resetStore();
  };

  return (
    <AppBar
      position="sticky"
      color="inherit"
      elevation={1}
      className={classes.appBar}
    >
      <Toolbar variant="dense" disableGutters={isMobile}>
        {!searchOpen && (
          <Container disableGutters className={classes.contentContainer}>
            <div className={classes.leftPortion}>
              <div className={classes.logoWrapper}>
                {isMobile && <NavMenuMobile />}
                {isMobile ? (
                  <IconButton
                    className={classes.logo}
                    component={RouterLink}
                    to="/"
                  >
                    <img src={SofLogo} width="25px" alt="sof-logo" />
                  </IconButton>
                ) : (
                  <Button
                    className={classes.logo}
                    component={RouterLink}
                    to="/"
                    size="large"
                  >
                    <img
                      src={SofLogo}
                      width="28px"
                      alt="sof-logo"
                      style={{ marginRight: '5px' }}
                    />
                    stack<strong>underflow</strong>
                  </Button>
                )}
                {!isMobile && (
                  <Typography variant="caption" color="secondary">
                    | Made with{' '}
                    <FavoriteIcon style={{ fontSize: 10, color: '#f4649f' }} />{' '}
                    by
                    <Link
                      href={'https://github.com/amand33p'}
                      color="inherit"
                      target="_blank"
                      rel="noopener"
                    >
                      <strong>{` amand33p`}</strong>
                    </Link>
                  </Typography>
                )}
              </div>
              {!isMobile && <SearchBar />}
            </div>
            {isMobile ? (
              <>
                <IconButton
                  color="primary"
                  className={classes.searchBtn}
                  onClick={() => setSearchOpen((prevState) => !prevState)}
                >
                  <SearchIcon />
                </IconButton>
                <DarkModeSwitch />
                <UserMenuMobile user={user} logoutUser={handleLogout} />
              </>
            ) : (
              <>
                <UserMenuDesktop user={user} logoutUser={handleLogout} />
                <DarkModeSwitch />
              </>
            )}
          </Container>
        )}
        {searchOpen && isMobile && (
          <SearchBar isMobile={isMobile} setSearchOpen={setSearchOpen} />
        )}
      </Toolbar>
    </AppBar>
  );
}
Example #10
Source File: link-form.js    From stacker.news with MIT License 4 votes vote down vote up
export function LinkForm ({ item, editThreshold }) {
  const router = useRouter()
  const client = useApolloClient()

  const [getPageTitle, { data }] = useLazyQuery(gql`
    query PageTitle($url: String!) {
      pageTitle(url: $url)
    }`, {
    fetchPolicy: 'network-only'
  })
  const [getDupes, { data: dupesData }] = useLazyQuery(gql`
  ${ITEM_FIELDS}
  query Dupes($url: String!) {
    dupes(url: $url) {
      ...ItemFields
    }
  }`, {
    fetchPolicy: 'network-only'
  })

  const [upsertLink] = useMutation(
    gql`
      mutation upsertLink($id: ID, $title: String!, $url: String!, $boost: Int, $forward: String) {
        upsertLink(id: $id, title: $title, url: $url, boost: $boost, forward: $forward) {
          id
        }
      }`
  )

  const LinkSchema = Yup.object({
    title: Yup.string().required('required').trim(),
    url: Yup.string().matches(URL, 'invalid url').required('required'),
    ...AdvPostSchema(client)
  })

  return (
    <Form
      initial={{
        title: item?.title || '',
        url: item?.url || '',
        ...AdvPostInitial
      }}
      schema={LinkSchema}
      onSubmit={async ({ boost, ...values }) => {
        const { error } = await upsertLink({
          variables: { id: item?.id, boost: Number(boost), ...values }
        })
        if (error) {
          throw new Error({ message: error.toString() })
        }
        if (item) {
          await router.push(`/items/${item.id}`)
        } else {
          await router.push('/recent')
        }
      }}
      storageKeyPrefix={item ? undefined : 'link'}
    >
      <Input
        label='title'
        name='title'
        overrideValue={data?.pageTitle}
        required
      />
      <Input
        label='url'
        name='url'
        required
        autoFocus
        hint={editThreshold
          ? <div className='text-muted font-weight-bold'><Countdown date={editThreshold} /></div>
          : null}
        onChange={async (formik, e) => {
          if ((/^ *$/).test(formik?.values.title)) {
            getPageTitle({
              variables: { url: e.target.value }
            })
          }
          getDupes({
            variables: { url: e.target.value }
          })
        }}
      />
      {!item && <AdvPostForm />}
      <ActionTooltip>
        <SubmitButton variant='secondary' className='mt-3'>{item ? 'save' : 'post'}</SubmitButton>
      </ActionTooltip>
      {dupesData?.dupes?.length > 0 &&
        <div className='mt-3'>
          <AccordianItem
            show
            headerColor='#c03221'
            header={<div style={{ fontWeight: 'bold', fontSize: '92%' }}>dupes</div>}
            body={
              <div>
                {dupesData.dupes.map((item, i) => (
                  <Item item={item} key={item.id} />
                ))}
              </div>
              }
          />
        </div>}

    </Form>
  )
}
Example #11
Source File: user-header.js    From stacker.news with MIT License 4 votes vote down vote up
export default function UserHeader ({ user }) {
  const [editting, setEditting] = useState(false)
  const me = useMe()
  const router = useRouter()
  const client = useApolloClient()
  const [setName] = useMutation(NAME_MUTATION)

  const isMe = me?.name === user.name
  const Satistics = () => <div className={`mb-2 ml-0 ml-sm-1 ${styles.username} text-success`}>{isMe ? `${user.sats} sats \\ ` : ''}{user.stacked} stacked</div>

  const UserSchema = Yup.object({
    name: Yup.string()
      .required('required')
      .matches(/^[\w_]+$/, 'only letters, numbers, and _')
      .max(32, 'too long')
      .test({
        name: 'name',
        test: async name => {
          if (!name || !name.length) return false
          const { data } = await client.query({ query: NAME_QUERY, variables: { name }, fetchPolicy: 'network-only' })
          return data.nameAvailable
        },
        message: 'taken'
      })
  })

  const lnurlp = encodeLNUrl(new URL(`https://stacker.news/.well-known/lnurlp/${user.name}`))

  return (
    <>
      <div className='d-flex mt-2 flex-wrap flex-column flex-sm-row'>
        <div className='position-relative' style={{ width: 'fit-content' }}>
          <Image
            src={user.photoId ? `https://${process.env.NEXT_PUBLIC_AWS_UPLOAD_BUCKET}.s3.amazonaws.com/${user.photoId}` : '/dorian400.jpg'} width='135' height='135'
            className={styles.userimg}
          />
          {isMe && <PhotoEditor userId={me.id} />}
        </div>
        <div className='ml-0 ml-sm-1 mt-3 mt-sm-0 justify-content-center align-self-sm-center'>
          {editting
            ? (
              <Form
                schema={UserSchema}
                initial={{
                  name: user.name
                }}
                validateImmediately
                onSubmit={async ({ name }) => {
                  if (name === user.name) {
                    setEditting(false)
                    return
                  }
                  const { error } = await setName({ variables: { name } })
                  if (error) {
                    throw new Error({ message: error.toString() })
                  }
                  router.replace({
                    pathname: router.pathname,
                    query: { ...router.query, name }
                  })

                  client.writeFragment({
                    id: `User:${user.id}`,
                    fragment: gql`
                  fragment CurUser on User {
                    name
                  }
                `,
                    data: {
                      name
                    }
                  })

                  setEditting(false)
                }}
              >
                <div className='d-flex align-items-center mb-2'>
                  <Input
                    prepend=<InputGroup.Text>@</InputGroup.Text>
                    name='name'
                    autoFocus
                    groupClassName={styles.usernameForm}
                    showValid
                  />
                  <SubmitButton variant='link' onClick={() => setEditting(true)}>save</SubmitButton>
                </div>
              </Form>
              )
            : (
              <div className='d-flex align-items-center mb-2'>
                <div className={styles.username}>@{user.name}</div>
                {isMe &&
                  <Button className='py-0' style={{ lineHeight: '1.25' }} variant='link' onClick={() => setEditting(true)}>edit nym</Button>}
              </div>
              )}
          <Satistics user={user} />
          <ModalButton
            clicker={
              <Button className='font-weight-bold ml-0 ml-sm-2'>
                <LightningIcon
                  width={20}
                  height={20}
                  className='mr-1'
                />{user.name}@stacker.news
              </Button>
            }
          >
            <a className='d-flex m-auto p-3' style={{ background: 'white', width: 'fit-content' }} href={`lightning:${lnurlp}`}>
              <QRCode className='d-flex m-auto' value={lnurlp} renderAs='svg' size={300} />
            </a>
            <div className='text-center font-weight-bold text-muted mt-3'>click or scan</div>
          </ModalButton>
        </div>
      </div>
      <Nav
        className={styles.nav}
        activeKey={router.asPath.split('?')[0]}
      >
        <Nav.Item>
          <Link href={'/' + user.name} passHref>
            <Nav.Link>bio</Nav.Link>
          </Link>
        </Nav.Item>
        <Nav.Item>
          <Link href={'/' + user.name + '/posts'} passHref>
            <Nav.Link>{user.nitems} posts</Nav.Link>
          </Link>
        </Nav.Item>
        <Nav.Item>
          <Link href={'/' + user.name + '/comments'} passHref>
            <Nav.Link>{user.ncomments} comments</Nav.Link>
          </Link>
        </Nav.Item>
        {isMe &&
          <Nav.Item>
            <Link href='/satistics?inc=invoice,withdrawal' passHref>
              <Nav.Link eventKey='/satistics'>satistics</Nav.Link>
            </Link>
          </Nav.Item>}
      </Nav>
    </>
  )
}