@apollo/client#useQuery JavaScript Examples

The following examples show how to use @apollo/client#useQuery. 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: Character.jsx    From web-frontend with MIT License 6 votes vote down vote up
Character = (props) => {
  const { loading, error, data, refetch, networkStatus } = useQuery(QUERY, {
    variables: { name: props.name },
    notifyOnNetworkStatusChange: true,
  });

  // const [getAlive, { filteredData, filtering }] = useLazyQuery(FILTERED_QUERY);
  // const [finalData, setFinalData] = useState(null);

  if (networkStatus === 4) return <p>Refetching...</p>;
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Character not found!</p>;

  return (
    <div>
      <button onClick={() => refetch()}>Actualizar</button>

      {data.characters.results.map((ch) => (
        <p key={ch.id}>{ch.name}</p>
      ))}
    </div>
  );
}
Example #2
Source File: index.js    From gatsby-apollo-wpgraphql-jwt-starter with MIT License 6 votes vote down vote up
DashboardIndex = () => {
  const { data, loading, error, refetch } = useQuery(GET_USER)
  const [user, setUser] = useUser();


  useEffect(() => {
    if (data) {
      setUser({
        ...user,
        username: data.viewer.username,
        firstName: data.viewer.firstName,
        lastName: data.viewer.lastName,
        email: data.viewer.email,
      })
    }

  }, [data])

  if (loading) return <ProgressLoader/>

  return (
    <>
      <Seo title="Dashboard"/>
      <h2>Dashboard Index</h2>

      <div>
        Hello {data && user && (user.firstName ? user.firstName + " " + user.lastName : user.email)}
      </div>
    </>
  )
}
Example #3
Source File: Table.js    From Simplify-Testing-with-React-Testing-Library with MIT License 6 votes vote down vote up
Table = () => {
  const { loading, error, data } = useQuery(EMPLOYEES)

  if (loading) return <p>Loading...</p>
  if (error) return <p>There was an Error</p>

  return (
    <table className="table table-striped">
      <thead className="thead-dark">
        <tr>
          <th scope="col">Name</th>
          <th scope="col">Department</th>
          <th scope="col">Title</th>
        </tr>
      </thead>
      <tbody>
        {data.employees.map(employee => {
          return <Row key={employee.id} {...employee} />
        })}
      </tbody>
    </table>
  )
}
Example #4
Source File: Permissions.js    From malware-detection-frontend with Apache License 2.0 6 votes vote down vote up
export function Permissions (props) {
    const intl = useIntl();
    const { data, loading } = useQuery(GET_MALWARE_COUNT);
    const PERMS = {
        access: ['malware-detection:*:*', 'malware-detection:*:read']
    };
    const permsAccess = usePermissions('malware-detection', PERMS.access);

    !loading && hasMalware(Number(data?.ruleStats?.matchedCount) !== 0);

    if (permsAccess?.isLoading) {
        return <Loading />;
    } else if (!permsAccess?.hasAccess) {
        return <NoPerms />;
    } else if (!permsAccess?.isLoading && permsAccess?.hasAccess) {
        return <React.Fragment>
            { !loading && hasMalware() && <Banner variant="danger" className='ins-l-malwareBanner'>{intl.formatMessage(messages.weDetected)}</Banner>}
            { props.children}
        </React.Fragment>;
    }
}
Example #5
Source File: TransactionHistory.js    From ucurtmetre with GNU General Public License v3.0 6 votes vote down vote up
function TransactionHistory() {
  const { data, loading, error } = useQuery(GET_LATEST_DONATIONS);

  const renderContent = () => {
    if (loading) {
      return (
        <div>
          <Skeleton height={43} />
          <Skeleton count={10} style={{ marginTop: '10px' }} />
        </div>
      );
    }

    if (error) {
      return (
        <Alert
          message="Bir hata oluştu. Lütfen sayfayı yenileyerek tekrar deneyiniz."
          variant="danger"
        />
      );
    }

    return (
      <TransactionHistoryTable data={data.allCampaignDetails.transactions} />
    );
  };

  return (
    <Card
      className="transaction-history"
      title="İşlem Geçmişi"
      desc="Öğrencilere destek olması için hazırladığımız akıllı algoritmamız ile hangi işlemler yapıldığının kısa bir özetine bu sayfadan ulaşabilirsiniz."
    >
      {renderContent()}
    </Card>
  );
}
Example #6
Source File: Sessions.jsx    From Consuming-GraphqL-Apollo with MIT License 6 votes vote down vote up
function AllSessionList() {
  const { loading, error, data } = useQuery(ALL_SESSIONS);

    if (loading) return <p>Loading Sessions..</p>
  
    if (error) return <p>Error loading sessions!</p>

    return data.sessions.map((session) => (
      <SessionItem
        key={session.id}
        session={{
          ...session
        }}
      />
    ));
}
Example #7
Source File: HeaderFavoriteProductsCount.js    From ReactNativeApolloOnlineStore with MIT License 6 votes vote down vote up
export function HeaderFavoriteProductsCount() {
  const {data} = useQuery(GET_FAVORITE_PRODUCTS_COUNT);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>{data.favoriteProductsCount}</Text>
    </View>
  );
}
Example #8
Source File: index.js    From nextjs-boilerplate with MIT License 6 votes vote down vote up
ViewDocument = () => {
  const router = useRouter();
  const documentId = router.query && router.query._id;
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const { data } = useQuery(documentQuery, { variables: { documentId }, fetchPolicy: 'network-only' });

  useEffect(() => {
    if (data && data.document) {
      setTitle(data.document && data.document.title);
      setContent(data.document && data.document.content);
    }
  }, [data]);

  return (
    <StyledViewDocument>
      <div className="page-header">
        <h5>{title}</h5>
        <button
          className="btn btn-primary"
          onClick={() => router.push(`/documents/${documentId}/edit`)}
        >
          Edit Document
        </button>
      </div>
      <div className="content">{content}</div>
    </StyledViewDocument>
  );
}
Example #9
Source File: metrics.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
Metrics = () => {
  const {loading, error, data} = useQuery(query);
  const [newMetricName, setNewMetricName] = useState("");
  const [addMetric, { loading: mutationLoading }] = useMutation(addMetricMutation, {
    awaitRefetchQueries: true,
    refetchQueries: [{query}],
  });

  const metrics = data?.queryMetric || []

  return <>
    <Navbar title="Metrics" color="primary" />
    <Content>
      {loading && <Backdrop open={loading || mutationLoading} >
        <CircularProgress />
      </Backdrop>}
      {error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
      <Card style={{ padding: 30 }}>
        <Typography>Here are the metrics currently configured:</Typography>
        <List>
          {metrics.map(({ name }, index) => <ListItem item key={index} sm={12} md={6} lg={3}>
            <Typography>{name}</Typography>
          </ListItem>)}
        </List>

        <TextField
          label="Add Metric"
          defaultValue={newMetricName}
          onChange={e => setNewMetricName(e.target.value)}
        />
        <UglyButton onClick={() => addMetric({ variables: { newMetricName } })} disabled={newMetricName === ""}>
          Add Metric
        </UglyButton>
      </Card>
    </Content>
  </>
}
Example #10
Source File: withBusinessPage.js    From horondi_admin with MIT License 6 votes vote down vote up
withBusinessPage = (Component) => (props) => {
  const styles = useStyles();
  const { data, loading } = useQuery(
    getBusinessTextByCodeWithPopulatedTranslationsKey,
    {
      variables: {
        code: labels.aboutUs.code
      }
    }
  );

  if (loading) {
    return <LoadingBar />;
  }

  return (
    <div className={styles.container}>
      {data?.getBusinessTextByCodeWithPopulatedTranslationsKey ? (
        <Component
          businessPage={data.getBusinessTextByCodeWithPopulatedTranslationsKey}
          {...props}
        />
      ) : null}
    </div>
  );
}
Example #11
Source File: chat.spec.js    From horondi_client_fe with MIT License 6 votes vote down vote up
describe('chat tests', () => {
  useQuery.mockImplementation(() => ({
    ...useQueryData
  }));

  beforeEach(() => {
    wrapper = shallow(<Chat />);
  });

  it('Should render chat', () => {
    expect(wrapper).toBeDefined();
  });

  it('Should render button', () => {
    const button = wrapper.find('button');

    expect(button).toBeDefined();
  });

  it('Button should be disabled', () => {
    wrapper.find('button').prop('onClick')();

    expect(wrapper.find('button').prop('disabled')).toBe(true);
  });
});
Example #12
Source File: index.js    From realworld with MIT License 6 votes vote down vote up
function EditorPage() {
  const router = useRouter();
  const page = useQuery(EditorPageQuery, {
    onCompleted: useCallback(
      data => {
        if (data.viewer?.canCreateArticle.value) return;

        router.replace(router.asPath, '/', { shallow: true });
      },
      [router]
    ),
  });
  const [createArticle] = useMutation(EditorPageCreateArticleMutation);

  if (page.networkStatus === NetworkStatus.loading) return null;

  return (
    <Layout {...page.data.viewer}>
      <div className="editor-page">
        <ArticleForm
          onSubmit={(values, { setSubmitting, setStatus }) => {
            createArticle({ variables: values })
              .then(res => {
                router.push(
                  '/article/[slug]',
                  `/article/${res.data.createArticle.article.slug}`
                );
              })
              .catch(err => {
                handleValidationError(err, setStatus);
                console.error(err);
                setSubmitting(false);
              });
          }}
        />
      </div>
    </Layout>
  );
}
Example #13
Source File: 03-use-apollo-get.js    From graphql-pokeapi with MIT License 6 votes vote down vote up
Todos = () => {
  const { loading, error, data } = useQuery(GET_POKEMONS, {
    variables: gqlVariables,
  });

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  console.log('Response from server', data);
  return 'Success!';
}
Example #14
Source File: errorHandling.js    From generator-webapp-rocket with MIT License 6 votes vote down vote up
export function useQueryWithErrorHandling(query, { onError = emptyFunction, ...props } = {}) {
  const showError = useError();
  const errorHandler = useCallback((error) => {
    onError()
    showError(error);
  }, [onError, showError])

  return useQuery(query,
    {
      ...props,
      onError: errorHandler
    }
  );
}
Example #15
Source File: comments-flat.js    From stacker.news with MIT License 6 votes vote down vote up
export default function CommentsFlat ({ variables, comments, cursor, ...props }) {
  const { data, fetchMore } = useQuery(MORE_FLAT_COMMENTS, {
    variables
  })

  if (!data && !comments) {
    return <CommentsFlatSkeleton />
  }

  if (data) {
    ({ moreFlatComments: { comments, cursor } } = data)
  }

  return (
    <>
      {comments.map(item =>
        <CommentFlat key={item.id} item={item} {...props} />
      )}
      <MoreFooter cursor={cursor} fetchMore={fetchMore} Skeleton={CommentsFlatSkeleton} />
    </>
  )
}
Example #16
Source File: asideCategories.js    From next-ecommerce with MIT License 5 votes vote down vote up
export default function AsideCategories() {
  const { data, loading, error } = useQuery(CATEGORIES);

  if (loading) return <></>;

  // Offline data
  if (!data?.categories || error)
    return (
      <ul className="categories">
        {offlineCategories.map((category) => {
          return <CategoriesItem key={category.id} category={category} />;
        })}

        <style jsx>{`
          .categories {
            width: 255px;
            max-width: 255px;
            background: #ffff;
            border-radius: 6px;
            margin-bottom: 30px;
            box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.05);
          }
          @media (max-width: 1000px) {
            .categories {
              display: none;
            }
          }
        `}</style>
      </ul>
    );

  return (
    <ul className="categories">
      {data.categories.map((category) => {
        return <CategoriesItem key={category.id} category={category} />;
      })}

      <style jsx>{`
        .categories {
          width: 255px;
          max-width: 255px;
          background: #ffff;
          border-radius: 6px;
          margin-bottom: 30px;
          box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.05);
        }
        @media (max-width: 1000px) {
          .categories {
            display: none;
          }
        }
      `}</style>
    </ul>
  );
}
Example #17
Source File: Details.js    From malware-detection-frontend with Apache License 2.0 5 votes vote down vote up
Details = () => {
    const intl = useIntl();
    const [isCodeEditorEnabled] = React.useState(false);
    const { id: sigId } = useParams();
    const breadcrumbs = [{ name: intl.formatMessage(messages.malwareDetectionSignatures),
        to: `${isBeta()}/insights/malware` }, { name: sigId, to: '#' }];
    const { data, loading } = useQuery(GET_SIGNATURE_DETAILS_PAGE, {
        variables: { ruleName: sigId  }
    });
    const sigDetailsData = data?.rulesList[0];
    const detailBlock = (title, detail) => <React.Fragment>
        <p className='ins-l-detailBlockHeader'>{title}</p>
        <p>{detail}</p>
    </React.Fragment>;

    return <React.Fragment>
        <PageHeader>
            <Breadcrumb items={breadcrumbs} />
            <Grid hasGutter>
                <GridItem md={12} sm={12}>
                    <Title headingLevel='h1' size={TitleSizes['3xl']} >{sigId}</Title>
                </GridItem>

                {isCodeEditorEnabled && (<GridItem md={7} sm={12}>
                    { sigDetailsData && <CodeEditor height='250px' code={sigDetailsData.rawRule} isReadOnly isDownloadEnabled isCopyEnabled />}
                </GridItem>)}

                {loading ? <Loading /> :
                    <GridItem md={isCodeEditorEnabled && 5 || 12} sm={12}>
                        <Grid hasGutter>
                            <GridItem xl2={isCodeEditorEnabled && 6 || 1} xl={isCodeEditorEnabled && 6 || 3} md={6} xs={12}>
                                {detailBlock(intl.formatMessage(messages.lastmatch), sigDetailsData?.lastMatchDate ?
                                    <DateFormat date={new Date(sigDetailsData.lastMatchDate)} type="onlyDate" />
                                    : intl.formatMessage(messages.never))}
                            </GridItem>
                            <GridItem xl2={isCodeEditorEnabled && 6 || 1} xl={isCodeEditorEnabled && 6 || 3} md={6} xs={12}>
                                {detailBlock(intl.formatMessage(messages.hostmatch),
                                    <span>{`${sigDetailsData?.affectedHosts?.totalCount}/${data?.hosts?.totalCount}`}</span>)}
                            </GridItem>
                            {isCodeEditorEnabled && <GridItem xl2={6} xl={6} md={6} xs={12}>
                                {detailBlock(intl.formatMessage(messages.description), sigDetailsData?.metadata?.description)}
                            </GridItem>}
                            <GridItem xl2={isCodeEditorEnabled && 6 || 1} xl={isCodeEditorEnabled && 6 || 3} md={6} xs={12}>
                                {detailBlock(intl.formatMessage(messages.enablement), sigDetailsData && <StatusLabel {...sigDetailsData} />)}
                            </GridItem>
                            <GridItem xl2={isCodeEditorEnabled && 6 || 2} xl={isCodeEditorEnabled && 6 || 3} md={6} xs={12}>
                                {detailBlock(intl.formatMessage(messages.author), sigDetailsData?.metadata?.author)}
                            </GridItem>
                            {!isCodeEditorEnabled && <GridItem xl2={7} xl={3} md={6} xs={12}>
                                {detailBlock(intl.formatMessage(messages.description), sigDetailsData?.metadata?.description)}
                            </GridItem>}
                        </Grid>
                    </GridItem>
                }
            </Grid>
        </PageHeader>
        <Main>
            <Title className='ins-l-tableBlockHeader' headingLevel='h1' size={TitleSizes['3xl']}>
                {intl.formatMessage(messages.affectedHosts)}
            </Title>
            <SigDetailsTable
                ruleName={sigId}
                isEmptyAccount={data?.hosts?.totalCount === 0}
                affectedCount={sigDetailsData?.affectedHosts?.totalCount}
            />
        </Main>
    </React.Fragment>;
}
Example #18
Source File: Resume.js    From resume-github with MIT License 5 votes vote down vote up
function Resume({ titleColor }) {
  const {
    config: {
      repositories: { showPinned },
    },
  } = useContext(ConfigContext);
  const { username } = useParams();
  const { loading, error, data } = useQuery(PUBLIC_USER_DETAILS, {
    variables: { username },
  });
  const [repo, setRepo] = useState(false);

  useEffect(() => {
    setRepo(showPinned);
  }, [showPinned]);

  if (loading) return <Loader />;
  if (error)
    return (
      <div>
        <p>Unexpected Error: Invalid Username or API error {console.log(error)}</p>
        <Link to="/">Go back</Link>
      </div>
    );
  return (
    <Main id="resume">
      {/* {console.log(data)} */}
      <Introduction
        name={data.user.name}
        username={username}
        bio={data.user.bio}
        avatarUrl={data.user.avatarUrl}
        location={data.user.location}
        createdAt={data.user.createdAt}
      />
      <Stats
        contributions={data.user.contributionsCollection}
        followers={data.user.followers.totalCount}
        following={data.user.following.totalCount}
        repoCount={data.user.repositories.totalCount}
        pkgCount={data.user.packages.totalCount}
        bountyHunter={data.user.isBountyHunter}
        campusExpert={data.user.isCampusExpert}
        devMember={data.user.isDeveloperProgramMember}
        employee={data.user.isEmployee}
        hireable={data.user.isHireable}
        githubUrl={data.user.url}
        websiteUrl={data.user.websiteUrl}
        starredRepoCount={data.user.starredRepositories.totalCount}
        titleColor={titleColor}
      />
      <Repositories
        repoList={repo ? data?.user?.pinnedItems?.nodes : data?.user?.repositories?.nodes}
        username={username}
        titleColor={titleColor}
      />
      {data.user.contributionsCollection.totalPullRequestContributions && (
        <Contributions
          repoList={data.user.contributionsCollection.pullRequestContributionsByRepository}
          titleColor={titleColor}
        />
      )}
      <Footer
        username={username}
        githubUrl={data.user.url}
        websiteUrl={data.user.websiteUrl}
        twitterUsername={data.user.twitterUsername}
      />
    </Main>
  );
}
Example #19
Source File: Donators.js    From ucurtmetre with GNU General Public License v3.0 5 votes vote down vote up
Donators = () => {
  const {
    data: corporateData,
    loading: corporateLoading,
    error: corporateError,
  } = useQuery(GET_CORPORATE_SPONSORS);
  const {
    data: individualData,
    loading: individualLoading,
    error: individualError,
  } = useQuery(GET_INDIVIDUAL_SPONSORS, { variables: { top: 6 } });

  const [activeTab, setActiveTab] = useState('Kurumsal');
  const toggleDonator = type => setActiveTab(type);

  if (corporateLoading || individualLoading) {
    return (
      <div className="widget-donators">
        <Skeleton width="148px" height="50px" />
        <Skeleton width="100%" height="342px" style={{ marginTop: 25 }} />
        <Skeleton width="250px" height="75px" style={{ marginTop: 25 }} />
      </div>
    );
  }

  if (corporateError || individualError) {
    return (
      <div className="widget-donators">
        <Alert
          message="Bir hata oluştu. Lütfen sayfayı yenileyerek tekrar deneyiniz."
          variant="danger"
        />
      </div>
    );
  }

  return (
    <div className="widget-donators">
      <nav>
        {tabs.map(tab => (
          <button
            type="button"
            className={cls({
              'button donator tab-buttons': true,
              active: activeTab === tab,
            })}
            key={tab}
            onClick={() => toggleDonator(tab)}
          >
            {tab}
          </button>
        ))}
      </nav>
      {activeTab === 'Kurumsal' && (
        <SponsorsTab sponsors={corporateData.corporateSponsors} />
      )}
      {activeTab === 'Bireysel' && (
        <IndividualTab individuals={individualData.individualSponsors} />
      )}
      <a
        href="https://ucurtmaprojesi.com/kampanyalar"
        className="button secondary-button blue-border fluid"
      >
        Kampanyaları Görüntüle
      </a>
    </div>
  );
}
Example #20
Source File: Sessions.jsx    From Consuming-GraphqL-Apollo with MIT License 5 votes vote down vote up
function SessionList ({ day }) {

  if (day == "") day = "Wednesday"

	// execute query and store response json
  const { loading, error, data } = useQuery(SESSIONS, {
    variables: {day}
  });
  
	if (loading) return <p>Loading Sessions..</p>

  if (error) return <p>Error loading sessions!</p>

	const results = [];

  results.push(data.intro.map((session) => (
    <SessionItem
      key={session.id}
      session={{
        ...session
      }}
    />
  )));
  
  results.push(data.intermediate.map((session) => (
    <SessionItem
      key={session.id}
      session={{
        ...session
      }}
    />
  )));
  
  results.push(data.advanced.map((session) => (
    <SessionItem
      key={session.id}
      session={{
        ...session
      }}
    />
  )));
  
  return results

}
Example #21
Source File: RightSidePanel.js    From stack-underflow with MIT License 5 votes vote down vote up
RightSidePanel = () => {
  const classes = useRightSidePanelStyles();
  const { notify } = useStateContext();
  const theme = useTheme();
  const isNotDesktop = useMediaQuery(theme.breakpoints.down('sm'));
  const { data, loading } = useQuery(GET_ALL_TAGS, {
    onError: (err) => {
      notify(getErrorMsg(err), 'error');
    },
  });

  if (isNotDesktop) return null;

  return (
    <Grid item>
      <div className={classes.rootPanel}>
        <div className={classes.content}>
          <div className={classes.tagsColumn}>
            <Typography variant="h6" color="secondary">
              Top Tags
            </Typography>
            {!loading && data ? (
              <div className={classes.tagsWrapper}>
                {data.getAllTags.slice(0, 26).map((t) => (
                  <div key={t.tagName}>
                    <Chip
                      label={
                        t.tagName.length > 13
                          ? t.tagName.slice(0, 13) + '...'
                          : t.tagName
                      }
                      variant="outlined"
                      color="primary"
                      size="small"
                      component={RouterLink}
                      to={`/tags/${t.tagName}`}
                      className={classes.tag}
                      clickable
                    />
                    <Typography
                      color="secondary"
                      variant="caption"
                    >{` × ${t.count}`}</Typography>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ minWidth: '200px' }}>
                <LoadingSpinner size={40} />
              </div>
            )}
          </div>
        </div>
      </div>
    </Grid>
  );
}
Example #22
Source File: ProductDetails.js    From ReactNativeApolloOnlineStore with MIT License 5 votes vote down vote up
export function ProductDetails({route}) {
  const {productId} = route.params;
  const {
    loading: productLoading,
    error: productError,
    data: productData,
  } = useQuery(GET_PRODUCT, {
    variables: {
      productId,
    },
    fetchPolicy: 'cache-first',
  });
  const {
    loading: commentsLoading,
    error: commentsError,
    data: commentsData,
  } = useQuery(GET_COMMENTS_BY_PRODUCT, {
    variables: {
      productId,
    },
    fetchPolicy: 'cache-and-network',
  });

  if (productLoading) {
    return <Loading hasBackground />;
  }

  if (productError) {
    return <Error error={productError} />;
  }

  function renderComment({item: comment}) {
    return (
      <Card id={comment.id} style={styles.commentCard}>
        <Text>{comment.comment}</Text>
      </Card>
    );
  }

  function renderNumberOfComments() {
    return (
      <Text style={styles.title}>
        {commentsData && commentsData.comments.length > 0
          ? `Comments [${commentsData.comments.length}]`
          : 'No comments found'}
      </Text>
    );
  }

  function renderHeader() {
    const {product} = productData;
    return (
      <>
        <Product product={product} />
        <AddComment productId={product.id} />
        {commentsLoading && <Loading />}
        {commentsError && <Error error={commentsError} />}
        {renderNumberOfComments()}
      </>
    );
  }

  return (
    <FlatList
      data={commentsData ? commentsData.comments : []}
      renderItem={renderComment}
      ListHeaderComponent={renderHeader()}
      contentContainerStyle={styles.commentsContainer}
    />
  );
}
Example #23
Source File: index.js    From nextjs-boilerplate with MIT License 5 votes vote down vote up
Documents = () => {
  const router = useRouter();
  const { loading, error, data } = useQuery(documentsQuery, {
    fetchPolicy: 'network-only'
  });

  if (error) {
    return <GraphQLError error={error} />;
  }

  return (
    <StyledDocuments>
      <div className="page-header">
        <h5>Documents</h5>
        <button
          className="btn btn-primary"
          onClick={() => router.push(`/documents/create`)}
        >
          Create Document
        </button>
      </div>
      {loading && <Loading />}
      {!loading && data.documents && data.documents.length > 0 && (
        <div className="table-responsive">
          <table className="table">
            <thead>
              <tr>
                <th>Title</th>
                <th className="text-center">Created At</th>
                <th className="text-center">Updated At</th>
                <th />
              </tr>
            </thead>
            <tbody>
              {data.documents.map(({ _id, title, createdAt, updatedAt }) => {
                return (
                  <tr key={_id} className="align-middle">
                    <td>
                      <Link href={`/documents/${_id}`}>{title}</Link>
                    </td>
                    <td className="text-center">{monthDayYear(createdAt)}</td>
                    <td className="text-center">{monthDayYear(updatedAt)}</td>
                    <td className="text-center">
                      <button
                        className="btn btn-primary btn-sm"
                        onClick={() => router.push(`/documents/${_id}/edit`)}
                      >
                        Edit
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
      {!loading && data.documents && data.documents.length === 0 && (
        <BlankState
          bordered
          title="No Documents Here."
          subtitle="To create your first document, click the button below. Once you create a document, it will appear here."
          action={{
            style: "primary",
            label: "Create Document",
            onClick: () => router.push(`/documents/create`),
          }}
        />
      )}
    </StyledDocuments>
  );
}
Example #24
Source File: add-data.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
AddData = ({currentTime = new Date()}) => {
  const {loading, error, data} = useQuery(query);
  const [date, setDate] = useState(currentTime.toISOString().substr(0, 10))
  const [values, setValues] = useState({})
  const [addCollectionMutation] = useMutation(addCollection);

  const metrics = data?.queryMetric || []

  const submitMetrics = async () => {
    const readings = Object.entries(values).map(([name, value]) => ({ value, metric: { name } }))
    await addCollectionMutation({ variables: {readings, date} })
    history.push("/");
  }

  return <>
    <Navbar title="Home" color="primary" />
    <Content>
      {loading && <Backdrop open={loading} >
        <CircularProgress />
      </Backdrop>}
      {error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
      <Grid container spacing={3}>
        <Grid item sm={12}>
          <Card style={{ padding: 30 }}>
            <TextField
              label="Date"
              type="date"
              defaultValue={date}
              InputLabelProps={{
                shrink: true,
              }}
              style={{ marginRight: 20 }}
              onChange={e => setDate(e.target.value)}
            />
          </Card>
        </Grid>
        {metrics.map(({ name }, index) => <Grid item key={index} sm={12} md={6} lg={3}>
          <Card style={{ textAlign: "center" }}>
            <CardContent>
              <TextField
                label={name}
                type="number"
                defaultValue={0}
                InputLabelProps={{
                  shrink: true,
                }}
                style={{ marginRight: 20 }}
                onChange={e => setValues({...values, [name]: e.target.value})}
              />
            </CardContent>
          </Card>
        </Grid>)}
        <Grid item sm={12} style={{textAlign: "right"}}>
          <UglyButton onClick={submitMetrics}>Add Readings</UglyButton>
        </Grid>
      </Grid>
    </Content>
  </>
}
Example #25
Source File: Forum.js    From ReactCookbook-source with MIT License 5 votes vote down vote up
Forum = () => {
  const {
    loading: messagesLoading,
    error: messagesError,
    data,
  } = useQuery(MESSAGES)
  const [addMessage] = useMutation(ADD_MESSAGE)
  const [text, setText] = useState()
  const [author, setAuthor] = useState()

  const messages = data && data.messages

  return (
    <div className="App">
      <input
        type="text"
        value={author}
        placeholder="Author"
        onChange={(evt) => setAuthor(evt.target.value)}
      />
      <textarea
        value={text}
        placeholder="Message"
        onChange={(evt) => setText(evt.target.value)}
      />
      <button
        onClick={async () => {
          try {
            await addMessage({
              variables: { author, text },
              refetchQueries: ['Messages'],
            })
            setText('')
            setAuthor('')
          } catch (err) {}
        }}
      >
        Post
      </button>
      {messagesError ? (
        <div className="error">
          Something went wrong:
          <div className="error-contents">
            {messagesError.message}
          </div>
        </div>
      ) : messagesLoading ? (
        <div className="loading">Loading...</div>
      ) : messages && messages.length ? (
        <dl>
          {messages.map((m) => (
            <>
              <dt>{m.author}</dt>
              <dd>{m.text}</dd>
            </>
          ))}
        </dl>
      ) : (
        'No messages'
      )}
    </div>
  )
}
Example #26
Source File: use-certificates.spec.js    From horondi_admin with MIT License 5 votes vote down vote up
useQuery.mockImplementation(() => ({
  loading: false,
  data: certificatesMock,
  refeth: jest.fn()
}));
Example #27
Source File: chat.js    From horondi_client_fe with MIT License 5 votes vote down vote up
Chat = () => {
  const [iconsVisible, setIconsVisible] = useState(false);
  const [mailFormVisible, setMailFormVisible] = useState(false);
  const [сhutButtonDisabled, setChutButtonDisabled] = useState(true);
  const style = useStyles({ iconsVisible, mailFormVisible });
  const cancelIconHandler = () => setMailFormVisible(!mailFormVisible);

  const { loading, error, data } = useQuery(getContactsForChat);
  if (loading || error) return errorOrLoadingHandler(error, loading);
  const contacts = data.getContacts.items;

  const chatButtonHendler = () => {
    setMailFormVisible(false);
    setIconsVisible(!iconsVisible);
    iconsVisible ? hideMessenger() : showMessenger(false);
  };

  return (
    <>
      <div className={style.fbChatWrapper}>
        <MessengerChat
          pageId={CHAT_FACEBOOK_DATA.pageId}
          appId={CHAT_FACEBOOK_DATA.appId}
          onClick={() => setMailFormVisible(false)}
          height={190}
          onMessengerLoad={() => {
            setChutButtonDisabled(false);
            hideMessenger();
          }}
        />
      </div>
      {iconsVisible && (
        <div className={style.iconsMessengers}>
          <div
            className={mailFormVisible ? style.msgIconActive : style.msgIcon}
            onClick={() => setMailFormVisible(!mailFormVisible)}
          >
            <MailOutlineIcon className={style.icon} />
          </div>
          <Transition
            initial={null}
            items={mailFormVisible}
            from={{ opacity: 0, height: 0 }}
            enter={{ opacity: 1, height: 0 }}
            leave={{ opacity: 0, height: 0 }}
            config={config.gentle}
          >
            {(item) =>
              item &&
              ((styles) => (
                <div style={styles}>
                  <MailForm
                    contacts={contacts}
                    cancelIconHandler={cancelIconHandler}
                    iconsVisible={iconsVisible}
                    mailFormVisible={mailFormVisible}
                  />
                </div>
              ))
            }
          </Transition>
        </div>
      )}
      <button onClick={chatButtonHendler} disabled={сhutButtonDisabled} className={style.chatIcon}>
        <ForumIcon className={style.icon} style={{ fontSize: 40 }} />
      </button>
    </>
  );
}
Example #28
Source File: index.js    From grandcast.fm with Apache License 2.0 5 votes vote down vote up
EpisodeFeed = () => {
  const FeedQuery = gql`
    {
      episodeFeed(first: 50) {
        id
        title
        audio
        podcast {
          title
          image
        }
        summary
        pubDate
        image
        link
      }
    }
  `

  const { data } = useQuery(FeedQuery)
  const { data: playlistData } = useQuery(PlaylistQuery)

  const { signOut } = useAuth()

  return (
    <div>
      <VStack spacing={8} w="100%">
        {data?.episodeFeed.map((v) => {
          return (
            <Episode
              key={v.id}
              episode={v}
              playlists={playlistData?.playlists}
            />
          )
          //return <li key={v.id}>{v.title}</li>
        })}
      </VStack>
      <button onClick={() => signOut()}>Sign Out</button>
    </div>
  )
}
Example #29
Source File: index.js    From realworld with MIT License 5 votes vote down vote up
function ArticlePage() {
  const router = useRouter();
  const skip = !router.query.slug;
  const page = useQuery(ArticlePageQuery, {
    variables: queryToVariables(router.query),
    skip,
  });

  const [deleteArticle] = useMutation(ArticlePageDeleteArticleMutation);
  const [favoriteArticle] = useMutation(ArticlePageFavoriteArticleMutation);
  const [followUser] = useMutation(ArticlePageFollowUserMutation);
  const [unfavoriteArticle] = useMutation(ArticlePageUnfavoriteArticleMutation);
  const [unfollowUser] = useMutation(ArticlePageUnfollowUserMutation);

  if (page.networkStatus === NetworkStatus.loading || skip) {
    return null;
  }

  return (
    <Layout {...page.data.viewer}>
      <div className="article-page">
        <ArticlePageBanner
          onDelete={deleteArticle}
          onFavorite={favoriteArticle}
          onFollow={followUser}
          onUnfavorite={unfavoriteArticle}
          onUnfollow={unfollowUser}
          {...page.data.article}
        />
        <div className="container page">
          <ArticleContent {...page.data.article} />
          <hr />
          <div className="article-actions">
            <ArticleMeta
              onDelete={deleteArticle}
              onFavorite={favoriteArticle}
              onFollow={followUser}
              onUnfavorite={unfavoriteArticle}
              onUnfollow={unfollowUser}
              {...page.data.article}
            />
          </div>
          <div className="row">
            <div className="col-xs-12 col-md-8 offset-md-2">
              <ArticleComments articleSlug={page.data.article.slug} />
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
}