@apollo/react-hooks#useQuery JavaScript Examples

The following examples show how to use @apollo/react-hooks#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: Resume.js    From resumeker-fe with MIT License 6 votes vote down vote up
function ResumeComponent(props) {
  const params = useParams();

  const classes = useStyles();

  console.log(params.draftID, "\n DraftID");

  const { data, loading, error } = useQuery(GET_DRAFT_QUERY, {
    variables: { draftID: params.draftID },
  });

  if (loading) return <div>Loading... </div>;

  if (error) return <div>Error: {error}</div>;

  console.log(data, "resume query response");

  const { getDraft } = data;
  return (
    <div className={classes.wrapper}>
      <Paper className={classes.paper}>
        <Grid>
          <div className={classes.name}>{getDraft.name}</div>
          <div>{getDraft.email}</div>
        </Grid>
        <Grid>Education</Grid>
        <Grid>Jobs</Grid>
        <Grid>Projects</Grid>
        <Grid>Tech Skills</Grid>
        <Grid>General Skills</Grid>
        <Grid>Languages</Grid>
        <Grid>Hobbies</Grid>
      </Paper>
    </div>
  );
}
Example #2
Source File: CategoryGrid.jsx    From trashpanda-fe with MIT License 6 votes vote down vote up
CategoryGrid = ({ searchFocus }) => {
  const history = useHistory();
  const categories = useQuery(GET_CATEGORIES);

  const handleCategoryClick = id => {
    history.push(`/category/${id}`);
  };
  return (
    <>
      {categories && categories.loading && <Spinner />}
      {categories && !categories.loading && (
        <GridContainer searchFocus={searchFocus}>
          {categories.data.families.map((category, key) => (
            <GridCard
              image={
                category.image_url.length > 0
                  ? category.image_url
                  : placeholderImg
              }
              name={category.description}
              key={key}
              onClick={() => handleCategoryClick(category.family_id)}
            />
          ))}
        </GridContainer>
      )}
    </>
  );
}
Example #3
Source File: List.jsx    From saasgear with MIT License 6 votes vote down vote up
ListDocument = () => {
  const history = useHistory();
  const { data, loading, refetch } = useQuery(getDocumentListQuery);

  function onFetchDocuments(offset, limit) {
    refetch({ offset, limit });
  }

  return (
    <div>
      <Header>
        <TitlePageStyle>Document</TitlePageStyle>
        <RightHeader>
          <SearchInput placeholder="Search.." />
          <CreateBtn
            color="primary"
            onClick={() => history.push('/document/create')}
          >
            <CreateBtnContent>Create New Document</CreateBtnContent>
            <CreateBtnContent mobile><AddIcon /></CreateBtnContent>
          </CreateBtn>
        </RightHeader>
      </Header>
      <ContentPage>
        <DocumentTable
          data={data?.getDocuments?.documents}
          total={data?.getDocuments?.count}
          loading={loading}
          onFetch={onFetchDocuments}
        />
      </ContentPage>
    </div>
  );
}
Example #4
Source File: DetailPageContainer.js    From mongodb-graphql-demo with Apache License 2.0 6 votes vote down vote up
function DetailPageContainer(props) {
	const id = props.match.params.id;

	const { loading, error, data } = useQuery(
		gql`
			{
				instapost(query: { _id: "${id}" }) {
					_id
					description
					imageUrl
				}
			}
		`
	);

	return (
		<div className="App">
			{loading && <Loading />}
			{error && <div>{`encountered an error: ${error}`}</div>}
			{data && <DetailPage {...data} {...props} />}
		</div>
	);
}
Example #5
Source File: Home.js    From 0.4.1-Quarantime with MIT License 6 votes vote down vote up
function Home() {
  const { user } = useContext(AuthContext);
  const {
    loading,
    data: { getPosts: posts }
  } = useQuery(FETCH_POSTS_QUERY);

  return (
    <Grid columns={1}>
      <Grid.Row className="page-title">
        <h1 id="quarantime">QUARANTIME</h1>
      </Grid.Row>
      <Grid.Row>
        {user && (
          <Grid.Column>
            <PostForm />
          </Grid.Column>
        )}
        {loading ? (
          <h1>Please wait..</h1>
        ) : (
          <Transition.Group>
            {posts &&
              posts.map((post) => (
                <Grid.Column key={post.id} style={{ marginBottom: 20, marginTop: 20 }}>
                  <PostCard post={post} />
                </Grid.Column>
              ))}
          </Transition.Group>
        )}
      </Grid.Row>
    </Grid>
  );
}
Example #6
Source File: Content.js    From spells-fyi with MIT License 6 votes vote down vote up
GridLayout = () => {
    /* 
    //  HTTP and WebSocket hooks
    //    - for http: useQuery
    //    - for ws: useSubscription
    */
    const { loading, error, data } = useQuery(spells())
    if (error) console.log(error)

    return (
        <Grid container direction="row" spacing={2}>
            <Grid item xs={12} sm={6}>
                <Typography variant="h2" align="center" color="textPrimary" paragraph>Timelocked</Typography>
                <Typography variant="h6" align="center" color="textSecondary" paragraph>This list of spells cannot be executed before the timelock ends.</Typography>
                <Content data={data && data.future} loading={loading} />
            </Grid>
            <Grid item xs={12} sm={6}>
                <Typography variant="h2" align="center" paragraph>Executed</Typography>
                <Typography variant="h6" align="center" color="textSecondary" paragraph>This list of spells has already been executed.</Typography>
                <Content data={data && data.past} loading={loading} />
            </Grid>
        </Grid>
    )
}
Example #7
Source File: index.js    From react-sample-projects with MIT License 6 votes vote down vote up
Home = () => {
  const dispatch = useDispatch();
  const { loading, error, data } = useQuery(GET_POKEMONS, {
    variables: { first: 100 },
  });

  if (loading) return <p>Loading ...</p>;
  if (error) return <pre>{error}</pre>;
  if (data) {
    dispatch({ type: 'SET_POKEMONS', payload: data.pokemons });
  }
  return (
    <div className="container pokemons">
      <PokemonListContainer />
    </div>
  );
}
Example #8
Source File: PostList.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
export default function PostList(props) {
  let params, search = "";
  if (props.location.search !== "") {
      params = queryString.parse(props.location.search)
      search = params.search;  
  } 
  let query = GET_FILTERED_BLOG_POSTS;
  if (search === "") {
    query = GET_ALL_BLOG_POSTS;
  }

  const {loading, error, data } = useQuery(query, {variables: { search }, fetchPolicy: "network-only"});
  if (loading) return "Fetching Posts...";
  if (error) return `Error: ${error}`;
  const posts = data.queryPost;
        
  return (
          <div className="container">
            {posts.map(post => (
              <Post key={post.postID} post={post} />
            ))}
          </div>
    );
}
Example #9
Source File: [slug].jsx    From dineforward with MIT License 6 votes vote down vote up
BusinessProfilePage = () => {
  const { query } = useRouter();
  const { loading, error, data } = useQuery(businessBySlug, {
    variables: { businessSlug: query.slug },
  });
  const classes = useStyles();
  if (error) return <h1>Error...</h1>;
  if (loading) return <span>Loading...</span>;
  if (data && data.allBusinesses.length > 0) {
    const business = data.allBusinesses[0];
    console.log(business);
    console.log(classes.heroBanner);
    return (
      <HomePageLayout>
        <AppNav />
        <HeroHeader image={business.heroImage.publicUrl} />
        <Container className={classes.root} maxWidth="lg">
          <h1>Business BY Slug</h1>
        </Container>
      </HomePageLayout>
    );
  } else {
    return <h1>Not found ${query.slug}</h1>;
  }
}
Example #10
Source File: apollo.js    From mailmask with GNU Affero General Public License v3.0 6 votes vote down vote up
useSafeQuery = (query, opts) => {
  const { loading, error, data, ...props } = useQuery(query, {
    fetchPolicy: 'cache-and-network',
    ...opts,
  })

  if ((data || error) && !loading) {
    const resolvedError = resolveError({ error, data })

    if (resolvedError) {
      return { error: constructUserFriendlyError(resolvedError), ...props }
    }
  }

  return { loading, data, ...props }
}
Example #11
Source File: RatingsChart.js    From willow-grandstack with Apache License 2.0 6 votes vote down vote up
export default function RatingsChart() {
  const theme = useTheme()

  const { loading, error, data } = useQuery(GET_DATA_QUERY)
  if (error) return <p>Sign in to view</p>
  if (loading) return <p>Loading</p>

  return (
    <React.Fragment>
      <Title>Average City Property Value</Title>
      <ResponsiveContainer>
        <BarChart
          data={data.cityValues}
          margin={{
            top: 16,
            right: 16,
            bottom: 0,
            left: 24,
          }}
        >
          <XAxis dataKey="city" stroke={theme.palette.text.secondary} />
          <YAxis stroke={theme.palette.text.secondary}>
            <Label
              angle={270}
              position="left"
              style={{ textAnchor: 'middle', fill: theme.palette.text.primary }}
            >
              City
            </Label>
          </YAxis>
          <Bar dataKey="average" fill={theme.palette.primary.main}></Bar>
        </BarChart>
      </ResponsiveContainer>
    </React.Fragment>
  )
}
Example #12
Source File: DefaultPod.jsx    From pods-frontend with MIT License 6 votes vote down vote up
export default function DefaultPod({ podName }) {
  const router = useRouter()

  let networkQuery = useQuery(gql`
  query {
    network @client {
      name
      chainId
    }
  }
`)

  let contractQuery = useQuery(gql`
    query {
      contract(name: podName) @client
    }
  `)

  let networkName

  if (networkQuery.data) {
    networkName = networkQuery.data.network.name
  }

  let podMessage = null
  if (contractQuery.data) {
    const { contract } = contractQuery.data
    podMessage = <p>
      <strong>{networkName} {podName} is at</strong>: {contract.address} <Link href="/pods/[podAddress]" as={`/pods/${contract.address}`}><a className='text-blue-500 hover:text-blue-300 underline trans'>View</a></Link>
    </p>
  }

  return (
    <div className='mb-8'>
      <p>Current Network: <b>{networkName}</b></p>
      {podMessage}
    </div>
  )
}
Example #13
Source File: Blog.js    From react-blog-github with MIT License 6 votes vote down vote up
Blog = () => {
  const [posts, setPosts] = useState([]);
  const { loading, error, data } = useQuery(GET_POSTS);

  useEffect(() => {
    if (!loading) {
      if (error) {
        console.error(error)
      }

      if (data) {
        setPosts(data?.repository?.issues?.nodes)
      }
    }
  }, [loading, error, data]);

  return (
    <>
      <Header />
      <BlogContainer>
        {
          loading
          ? <Loader />
          : posts.map((v, i) => {
              return <Card blog={v} key={i} />;
            })
        }
      </BlogContainer>
    </>
  );
}
Example #14
Source File: generalInfoComponent.js    From resumeker-fe with MIT License 5 votes vote down vote up
GeneralInfoComponent = (props) => {
  const [edit, setEdit] = useState(false);

  const classes = useStyles();

  const id = localStorage.getItem("draftID");
  const { loading, error, data } = useQuery(GET_DRAFT_QUERY, {
    variables: { id },
  });

  const [info, setInfo] = useState({
    email: "",
    name: "",
  });

  if (loading) return <p>loading</p>;
  if (error) return <p>ERROR: {error.message}</p>;
  if (!data) return <p>Not found</p>;

  console.log(data, "data inside of review General info");

  const saveInfo = (event) => {
    event.preventDefault();
    // props.addData(info);
    setEdit(false);
  };

  const onChange = (event) => {
    setInfo({ ...info, [event.target.name]: event.target.value });
  };

  if (data) {
    if (edit) {
      return (
        <Card>
          <h1>
            General Info{" "}
            <EditIcon color="primary" onClick={() => setEdit(!edit)}>
              Edit
            </EditIcon>
          </h1>
          <CardContent>
            <form onSubmit={saveInfo}>
              <ReviewGeneralInfoFormTemplate
                onChange={onChange}
                info={data.getDraft}
              />
              <Button
                type="submit"
                fullWidth
                variant="contained"
                color="primary"
                className={classes.submit}
              >
                Save
              </Button>
            </form>
          </CardContent>
        </Card>
      );
    } else {
      return (
        <Card>
          <h1>
            General Info{" "}
            <EditIcon color="disabled" onClick={() => setEdit(!edit)}>
              Edit
            </EditIcon>
          </h1>
          <CardContent className={classes.cardContent}>
            <p>Your Name: {data.getDraft.name}</p>
            <p>Email Address: {data.getDraft.email} </p>
          </CardContent>
        </Card>
      );
    }
  }
}
Example #15
Source File: MaterialPage.jsx    From trashpanda-fe with MIT License 5 votes vote down vote up
MaterialPage = () => {
  const history = useHistory();
  const { materialId } = useParams();

  const matInfo = useQuery(GET_MATERIAL, {
    variables: {
      materialId: parseInt(materialId)
    }
  });
  const [material, setMaterial] = useState({
    description: "",
    long_description: "",
    bin_trash: false,
    bin_recycle: false,
    bin_compost: false,
    dropoff: null,
    pickup: null,
    notes: null
  });

  useEffect(() => {
    if (matInfo.data && !matInfo.loading) {
      setMaterial(matInfo.data.material);
    }
  }, [matInfo.data]);

  if (matInfo.loading)
    return (
      <SpinnerContainer>
        <Spinner />
      </SpinnerContainer>
    );

  return (
    <Container>
      <Title>{material.description}</Title>
      <Badge
        type={getTypeString(
          material.bin_recycle,
          material.bin_compost,
          material.bin_trash
        )}
      />
      <ButtonContainer>
        <LocationButton
          onClick={() => history.push(`/material/${materialId}/locations`)}
        >
          Locate Centers
        </LocationButton>
      </ButtonContainer>
      <LongDescription>{material.long_description}</LongDescription>

      <SpecialText>{material.notes}</SpecialText>
    </Container>
  );
}
Example #16
Source File: EditTeam.jsx    From saasgear with MIT License 5 votes vote down vote up
export default function EditTeam() {
  const { teamId } = useParams();
  const { teams } = useSelector((state) => state.team);
  const [currentTeam, setCurrentTeam] = useState();
  const { data, loading } = useQuery(getTeamDetailQuery, {
    variables: { alias: teamId },
  });
  const dispatch = useDispatch();
  const history = useHistory();

  useEffect(() => {
    if (!loading) {
      dispatch(addTeamMember({ teamID: teamId, data: data?.getTeamDetail }));
    }
  }, [data, loading]);

  useEffect(() => {
    const team = teams.find((it) => it.teamID === teamId);
    if (teamId && team) {
      setCurrentTeam(team);
    } else {
      history.replace('/teams');
    }
  }, [teams]);

  return currentTeam ? (
    <>
      <TeamDetail team={currentTeam} />
      <TeamMember
        teamMembers={currentTeam.teamMembers.filter(
          (it) => it.status !== 'pending',
        )}
      />
      <InviteMember
        alias={teamId}
        teamMembers={currentTeam.teamMembers.filter(
          (it) => it.status === 'pending',
        )}
      />
    </>
  ) : (
    <div>Loading...</div>
  );
}
Example #17
Source File: index.js    From monorepo-starter with MIT License 5 votes vote down vote up
function HomePage() {
  const { data: authorList, initialLoading, initialError } = useQuery(
    getAuthors
  );
  const [getAuthor, { loading, error, data }] = useLazyQuery(getAuthorDetails);

  if (!authorList) {
    return null;
  }

  return (
    <div
      style={{
        textAlign: "center"
      }}
    >
      <Preamble />
      <h2>
        As a treat, we've got some cool author recs Click on an author to see
        some of their books:
      </h2>
      <div>
        {authorList.authors.map(({ name }) => (
          <Button
            key={name}
            isSelected={data && data.author.name === name}
            onClick={() => {
              getAuthor({ variables: { name } });
            }}
          >
            {name}
          </Button>
        ))}
      </div>
      <div style={{ marginTop: "24px" }}>
        {data ? (
          <div>
            <ul>
              {data.author.books.map(({ title }) => (
                <li style={{ listStyle: "none" }} key={title}>
                  {title}
                </li>
              ))}
            </ul>
          </div>
        ) : null}
      </div>
    </div>
  );
}
Example #18
Source File: ViewPost.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
export default function ViewPost(props) {
  const [numLikes, setNumLikes] = useState(0);
  const history = useHistory();
  const editPost = (postID) => {
    history.push({
      pathname: '/edit',
      search: `?postID=${postID}`
    })
  }
  const postSet = {
    numLikes: numLikes +1
  }
  let params = queryString.parse(props.location.search);
  let postID = params.postID;

  const { loading, error, data } = useQuery(GET_POST, { variables: { postID }, fetchPolicy: "network-only" });
  const [deletePost] = useMutation(DELETE_POST);
  const [updatePost] = useMutation(POST_MUTATION);

  if (loading) return "Fetching Posts...";
  if (error) return `Error: ${error}`;
  const post = data.getPost;
  if (numLikes === 0) {
    setNumLikes(post.numLikes)
  }

  return (
    <div className="container">
      <div className="h3 text-center">{post.title}
      <span className="delete-post" onClick={async e => {
          e.preventDefault();
          await deletePost({ variables: { postID } })
          history.push({
            pathname: '/'
          }); 
        }}>
          <i className="icon-trash" aria-hidden="true"></i>
        </span>
        <span className="edit-post" onClick={() => editPost(post.postID)}>
          <i className="icon-edit" aria-hidden="true"></i>
        </span>
      </div>
      <hr />
      <div className="text-post">{post.text}</div>
      <div>
        <button type="button" className="btn btn-primary btn-sm" onClick = { async e => {
          e.preventDefault()
          await updatePost({ variables: { postSet, postID} })
          history.push({
            pathname: '/',
          }); 
          history.push({
            pathname: '/view',
            search: `?postID=${postID}`
          });
        }}>
          Likes <span className="badge badge-light">{post.numLikes}</span>
        </button>
        <span className="tagsset-post">
          {post.tags.map(tag => (
            <span
              className="badge badge-secondary tag-post"
              key={tag}
            >
              {tag}
            </span>
          ))}
        </span>
      </div>
    </div>
  );
}
Example #19
Source File: coordinators.js    From project-avocado-web with MIT License 5 votes vote down vote up
render () {
    const GetCoordinators=()=> {
      const { data, loading, error } = useQuery(GET_COORDINATORS);
      return(
        <AgGridReact
        columnDefs={this.state.columnDefs}
        rowData={(loading || error)?data:data.coordinators}
        enableCellTextSelection={true}
        ensureDomOrder={true}
        >
      </AgGridReact>
      )  
    }
    return (
      <div>
        <div className="page-header">
          <h3 className="page-title">
            Coordinators
          </h3>
          <nav aria-label="breadcrumb">
            <ol className="breadcrumb">
              <li className="breadcrumb-item"><a href="!#" onClick={event => event.preventDefault()}>ICS Team</a></li>
              <li className="breadcrumb-item active" aria-current="page">Coordinators</li>
            </ol>
          </nav>
        </div>
        <div className="row">
          <div className="col-12 grid-margin stretch-card">
            <div className="card">
              <div className="card-body">
              <div style={{ height: '420px  ', width: '100%' }} className="ag-theme-alpine">
                <GetCoordinators/>
        </div>
              </div>
              </div>
          </div>
          </div>
      </div>
    );
  }
Example #20
Source File: NotificationStructure.js    From lifebank with MIT License 5 votes vote down vote up
NotificationStructure = ({ id, title, description, state, dateAndTime }) => {
  const classes = useStyles()
  const [name, setName] = useState()
  const [time, setTime] = useState()

  const { refetch: getData } = useQuery(GET_ACCOUNT_NAME, {
    variables: {
      account: description.substring(5, 17)
    },
    skip: true
  })

  const [editNotificationState, { }] = useMutation(EDIT_NOTIFICATION_STATE)

  useEffect(() => {
    const response = async () => {
      const { data } = await getData({ account: description.substring(5, 17) })
      setName(data.user[0].name)
    }
    response()
  }, [description])

  useEffect(() => {
    const hour = parseInt(dateAndTime.substring(11, 13)) - 6
    setTime(hour.toString() + dateAndTime.substring(13, 19))
  }, [dateAndTime])

  const changeNotificationState = () => {
    editNotificationState({
      variables: {
        id: id
      }
    })
  }

  return (
    <>
      <Button className={classes.wrapper} onMouseOver={changeNotificationState}>
        <Grid container xs={3}>
          <Grid item xs={12}>
            {state === true && (
              <NewNotificationIcon className={classes.iconOption} />
            )}
          </Grid>
        </Grid>
        <Grid container xs={11}>
          <Grid item xs={12}>
            <Typography className={classes.title}>
              {title}
            </Typography>
          </Grid>
          <Grid item xs={10}>
            <Typography className={classes.labelOption}>
              {description.replace(description.substring(5, 17), name)}
            </Typography>
          </Grid>
        </Grid>
        <Grid container xs={6}>
          <Grid item xs={12}>
            <Typography className={classes.labelOption}>
              {time}
              <br ></br>
              {dateAndTime.substring(5, 10) + "-" + dateAndTime.substring(0, 4)}
            </Typography>
          </Grid>
        </Grid>
      </Button>
    </>
  )
}
Example #21
Source File: BrowseRequests.jsx    From feedadoc with MIT License 5 votes vote down vote up
export default function BrowseRequests({ minimal = false }) {
  const classes = useStyles();
  const [pageType, setPageType] = React.useState("forward");
  const [endCursor, setEndCursor] = React.useState("");
  const [startCursor, setStartCursor] = React.useState("");
  const [searchValue, setSearchValue] = React.useState("");

  const { search } = useLocation();
  const isSuccess = search.includes("success=true");
  const resultsPerPage = 20;

  const { loading, error, data } = useQuery(TOTAL_PROVIDERS, {
    variables: {
      first: pageType === "forward" ? resultsPerPage : null,
      after: pageType === "forward" ? endCursor : null,
      last: pageType === "back" ? resultsPerPage : null,
      before: pageType === "back" ? startCursor : null,
      city: searchValue,
    },
  });

  const pageNext = (endCursor) => {
    setPageType("forward");
    setEndCursor(endCursor);
  };

  const pagePrevious = (startCursor) => {
    setPageType("back");
    setStartCursor(startCursor);
  };

  const changeSearchValue = (e) => {
    setSearchValue(e.target.value);
  };

  return (
    <Box mb={6} mt={10}>
      {isSuccess && (
        <Container className={classes.heroContent}>
          <Box mb={4} textAlign="center">
            <Typography variant="h5" className={classes.successText}>
              Thank you so much for volunteering!
            </Typography>
            <Typography variant="subtitle1" className={classes.successText}>
              You should hear back from the medical provider soon.
            </Typography>
          </Box>
        </Container>
      )}
      {!minimal && <VolunteerInstructions />}
      <Container>
        <Box className={classes.search}>
          <div className={classes.searchIcon}>
            <SearchIcon />
          </div>
          <InputBase
            placeholder="Search by city..."
            classes={{
              root: classes.inputRoot,
              input: classes.inputInput,
            }}
            inputProps={{ "aria-label": "search by city" }}
            value={searchValue}
            onChange={changeSearchValue}
          />
        </Box>
      </Container>
      <ProviderList
        providers={(data && data.providers.edges) || []}
        pageInfo={data && data.providers.pageInfo}
        onNext={pageNext}
        onPrevious={pagePrevious}
      />
      <Box mt={6}>
        <SocialDistanceNotice />
      </Box>
    </Box>
  );
}
Example #22
Source File: PathwayPreview.js    From pathways with GNU General Public License v3.0 5 votes vote down vote up
export default function PathwayPreview(props) {
    const { pathwayId } = props
    const FETCH_CONTENT_PATHWAY = gql`
        query {
            Pathway(id: "${pathwayId}") {
                id
                name
                steps {
                    id
                    name
                    time
                    index
                    isPathway
                    content {
                        id
                        title
                        content
                    }
                    pathway {
                        id
                    }
                }
            }
        }
    `
    const { data, loading, error } = useQuery(FETCH_CONTENT_PATHWAY, {
        variables: { pathwayId },
    })

    if (loading) return 'loading...'
    if (error) return 'ERROR fetching pathway'
    if ('Step' in data) {
        return
    }
    console.log(data)
    if (data.Pathway.length <= 0) return null
    let link = `/pathway?id=${data.Pathway[0].id}`

    let content = '# ' + data.Pathway[0].name

    data.Pathway[0].steps.forEach((step) => {
        content += '\n - ** ' + step.name + '** \n'
    })

    return (
        <Fragment>
            <div>
                <ReactMarkdown
                    source={content}
                    escapeHtml={false}
                    renderers={{ code: CodeBlock }}
                />
                <Link target='_blank' to={link} className={classes.link}>
                    View Full Pathway
                    <MdArrowRoundForward
                        fontSize='20px'
                        className={classes.icon}
                    />
                </Link>
            </div>
        </Fragment>
    )
}
Example #23
Source File: index.jsx    From teach-yourself-code with MIT License 5 votes vote down vote up
// Global styles and component-specific styles.

function Layout({ children }) {
  const { user, loading, error } = useFetchUser();
  const { data, loading: loadingId, error: idError } = useQuery(fetchUser, {
    variables: {
      sub: user ? user.sub : null,
    },
  });

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(updateCurrentUser(user));
    if (data) {
      dispatch(updatedUserId(data.users[0].id));
    }
  });

  return (
    <div>
      <div className="main-view is-flex is-hidden-touch">
        <div className="columns" style={{ width: "100%" }}>
          <div
            className="column is-2 is-hidden-mobile is-flex"
            style={{ justifyContent: "center" }}
          >
            <Sidebar user={user} loading={loading} className="is-flex" />
          </div>
          <div className="column view-column is-10">
            <View>{children}</View>
          </div>
        </div>
      </div>
      <div className="mobile-view is-hidden-desktop">
        <View style={{ position: "relative" }}>{children}</View>
        <BottomBar user={user} loading={loading} className="is-hidden-tablet" />
      </div>
    </div>
  );
}
Example #24
Source File: Search.js    From willow-grandstack with Apache License 2.0 5 votes vote down vote up
export default function Search() {
  const { loading, error, data } = useQuery(PROPERTY_SEARCH_QUERY)

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

  return <MapResults properties={data.Property} />
}
Example #25
Source File: PodUserDetails.jsx    From pods-frontend with MIT License 5 votes vote down vote up
export function PodUserDetails({ podAddress, userAddress }) {
  let pod = useQuery(podQuery, {
    variables: { podAddress },
  })

  let poolAddress = pod.data ? pod.data.poolAddress : null

  let podUser = useQuery(podUserQuery, {
    variables: { podAddress, userAddress },
    skip: !userAddress
  })

  let pool = useQuery(poolQuery, {
    variables: {
      podAddress,
      poolAddress
    },
    pollInterval: 2000,
    skip: !poolAddress
  })

  let tokenAddress = pool.data ? pool.data.tokenAddress : null

  const skipToken = !tokenAddress || !userAddress

  let token = useQuery(tokenQuery, {
    variables: {
      podAddress,
      userAddress,
      tokenAddress
    },
    pollInterval: skipToken ? 0 : 2000,
    skip: skipToken
  })

  let result = null
  if (podQuery.loading) {
    result = <div>Loading...</div>
  } else if (podQuery.error) {
    console.error(podQuery.error)
    result = <div>Error: {podQuery.error.message}</div>
  } else if (pod.data && pool.data) {
    const podData = pod.data
    const poolData = pool.data
    let tokenData
    if (token.data) {
      tokenData = token.data
    }
    let podUserData
    if (podUser.data) {
      podUserData = podUser.data
    }
    result = (
      <div>
        <p className='mb-1 font-mono'><span className='font-bold'>Pod Address</span>:&nbsp; <a className='text-blue-500 hover:text-blue-300 trans underline' href={`https://kovan.etherscan.io/address/${podAddress}`}>{podAddress}</a></p>
        <p className='mb-6 font-mono'><span className='font-bold'>Pool Address</span>: <a className='text-blue-500 hover:text-blue-300 trans underline' href={`https://kovan.etherscan.io/address/${podData.poolAddress}`}>{podData.poolAddress}</a></p>
        <p className='mb-1 font-mono'><span className='font-bold'>Pool Open Draw Id</span>:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {poolData.openDrawId.toString()}</p>
        <p className='mb-1 font-mono'><span className='font-bold'>Pool Committed Balance</span>: {ethers.utils.formatEther(poolData.committedBalance)}</p>
        <p className='mb-6 font-mono'><span className='font-bold'>Pool Open Balance</span>:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {ethers.utils.formatEther(poolData.openBalance)}</p>
        <p className='mb-1 font-mono'><span className='font-bold'>User's Address</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a className='text-blue-500 hover:text-blue-300 trans underline' href={`https://kovan.etherscan.io/address/${userAddress}`}>{userAddress}</a></p>
        <p className='mb-1 font-mono'><span className='font-bold'>User Token Balance</span>: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {tokenData ? ethers.utils.formatEther(tokenData.balance) : '?'}</p>
        <p className='mb-1 font-mono'><span className='font-bold'>User Pod Balance</span>:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {podUserData ? ethers.utils.formatEther(podUserData.balance) : '?'}</p>
        <p className='mb-1 font-mono'><span className='font-bold'>User Pod Balance (underyling)</span>: {podUserData ? ethers.utils.formatEther(podUserData.balanceUnderlying) : '?'}</p>
        <p className='mb-6 font-mono'><span className='font-bold'>User Pod Pending Deposit</span>:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {podUserData ? ethers.utils.formatEther(podUserData.pendingDeposit) : '?'}</p>
      </div>
    )
  }

  return result
}
Example #26
Source File: firstTimersOnlyIssue.js    From GSOD.Contributors_website with Mozilla Public License 2.0 5 votes vote down vote up
function GetIssues(props){
    const classes = useStyles();
    const {
    repo: [repo, setRepo]} = {repo: useState('GCBM.Visualisation_Tool'),...(props.state || {})};
    console.log({repo});
    const { loading, error, data } = useQuery(GET_LABELLED_ISSUES, {
      variables: { repo: repo},
    });
    //const { loading, error, data } = useQuery(GET_LABELLED_ISSUES, {variables: {state.name} ,});
    console.log(data);

    if (loading) return <p>Loading...</p>;
    console.log(error);
    if (error) return <p>Error :(</p>;

    return data.repository.issues.edges.map(({ node }) => (
      <div>
      <ListItem alignItems="flex-start">
        <ListItemAvatar>
          <Avatar alt={node.author.login} src={node.author.avatarUrl} />
        </ListItemAvatar>
        <ListItemLink href={node.url}>
        <ListItemText
          primary={node.title}
          secondary={
            <React.Fragment>
              <Typography
                component="span"
                variant="body2"
                className={classes.inline}
                color="textPrimary"
              >
                #{node.number}
              </Typography>
              " — " {node.createdAt}
            </React.Fragment>
          }
        />
        </ListItemLink>
      </ListItem>
      <Divider variant="inset" component="li" />
      </div>
    ));
  }
Example #27
Source File: App.js    From todo-react-graphql with MIT License 5 votes vote down vote up
function App() {
  let input;
  const { data, loading, error } = useQuery(READ_TODOS);
  const [createTodo] = useMutation(CREATE_TODO);
  const [deleteTodo] = useMutation(REMOVE_TODO);
  const [updateTodo] = useMutation(UPDATE_TODO);

  if (loading) return <p>loading...</p>;
  if (error) return <p>ERROR</p>;
  if (!data) return <p>Not found</p>;

  return (
    <div className="app">
      <h3>Create New Todo</h3>
      <form onSubmit={e => {
        e.preventDefault();
        createTodo({ variables: { text: input.value } });
        input.value = '';
        window.location.reload();
      }}>
        <input className="form-control" type="text" placeholder="Enter todo" ref={node => { input = node; }}></input>
        <button className="btn btn-primary px-5 my-2" type="submit">Submit</button>
      </form>
      <ul>
        {data.todos.map((todo) =>
          <li key={todo.id} className="w-100">
            <span className={todo.completed ? "done" : "pending"}>{todo.text}</span>
            <button className="btn btn-sm btn-danger rounded-circle float-right" onClick={() => {
              deleteTodo({ variables: { id: todo.id } });
              window.location.reload();
            }}>X</button>
            <button className={`btn btn-sm float-right ${todo.completed ? "btn-success" : "btn-info"}`} onClick={() => {
              updateTodo({ variables: { id: todo.id } });
              window.location.reload();
            }}>{todo.completed ? <span>Completed</span> : <span>Not completed</span>}</button>
          </li>
        )}
      </ul>
    </div>
  );
}
Example #28
Source File: LockPicker.jsx    From locked.fyi with MIT License 5 votes vote down vote up
LockPicker = ({ identity, onLockChange, currentLocks, children }) => {
  const { data, loading } = useQuery(locksByOwner(), {
    variables: {
      owner: identity,
    },
  })

  const locks = data && data.locks

  if (loading || !locks) {
    return <Loading />
  }
  const lockOptions = locks.map((lock) => ({
    value: lock.address,
    label: lock.name || lock.addresss,
  }))

  const selectedLocks = currentLocks
    ? lockOptions.filter((lock) => currentLocks.indexOf(lock.value) > -1)
    : []

  if (lockOptions.length > 0) {
    return (
      <>
        {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
        <label htmlFor="locks">Locks: </label>
        <LockSelect
          inputId="locks"
          isMulti
          isLoading={loading}
          value={selectedLocks}
          onChange={onLockChange}
          options={lockOptions}
          noOptionsMessage={() =>
            "You have not created any lock yet. You will use the community lock..."
          }
        />
      </>
    )
  }

  return children
}
Example #29
Source File: ticker.js    From about-1hive with GNU General Public License v3.0 4 votes vote down vote up
export default function Ticker() {
  //setup time constants
  dayjs.extend(utc)
  const utcCurrentTime = dayjs()
  const utcOneDayBack = utcCurrentTime.subtract(1, 'day').unix()
  const [initialized, updateInitialized] = useState(false)

  const { data: blockData } = useQuery(GET_BLOCK, {
    client: blockClient,
    variables: {
      timestamp: utcOneDayBack
    }
  })
  const oneDayBackBlock = blockData?.blocks?.[0]?.number
  const { loading, data } = useQuery(APOLLO_QUERY, { pollInterval: 10000, client: client })

  const [oneDayResult, setOnedayResult] = useState()

  useEffect(() => {
    async function getData() {
      let result = await client.query({
        query: UNISWAP_GLOBALS_24HOURS_AGO_QUERY(oneDayBackBlock),

        fetchPolicy: 'cache-first'
      })
      if (result) {
        setOnedayResult(result?.data?.uniswapFactory)
      }
    }
    if (oneDayBackBlock) {
      getData()
    }
  }, [oneDayBackBlock])

  const [totalElements] = useState(8)

  let UniStats = {
    key: function(n) {
      return this[Object.keys(this)[n]]
    }
  }

  if (data && oneDayResult) {
    const volume24Hour = parseFloat(data?.uniswapFactory?.totalVolumeUSD) - parseFloat(oneDayResult?.totalVolumeUSD)

    UniStats.volume = [
      new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        notation: 'compact',
        compactDisplay: 'short'
      }).format(volume24Hour),
      ' 24h Volume'
    ]
    UniStats.liquidity = [
      new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        notation: 'compact',
        compactDisplay: 'short'
        // maximumSignificantDigits: 5
      }).format(data.uniswapFactory.totalLiquidityUSD),
      ' Total Liquidity'
    ]
    UniStats.exchanges = [Number.parseFloat(data?.uniswapFactory?.pairCount), ' Total Pools']

    UniStats.ETHprice = [
      new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        notation: 'compact',
        compactDisplay: 'short',
        maximumSignificantDigits: 5
      }).format(parseFloat(data?.bundle?.ethPrice)),
      ' Uni ETH Price'
    ]
  }

  useLayoutEffect(() => {
    if (loading === false && UniStats.volume !== undefined) {
      updateInitialized(true)
    }
  }, [loading, UniStats.volume])

  useLayoutEffect(() => {
    initialized &&
      Marquee3k.init({
        selector: 'ticker' // define a custom classname
      })
  }, [initialized])

  return (
    initialized && (
      <MarqueeWrapper className="ticker" data-speed="0.25" data-pausable="true">
        <div>
          {Array.from({ length: totalElements }).map((_, idx) => {
            return <AnimatingEl stat={UniStats.key((idx % 4) + 1)} key={idx} />
          })}
        </div>
      </MarqueeWrapper>
    )
  )
}