react-instantsearch-dom#connectHits JavaScript Examples

The following examples show how to use react-instantsearch-dom#connectHits. 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: Algolia.js    From gatsby-airtable-design-project with BSD Zero Clause License 6 votes vote down vote up
NewHits = connectHits(({ hits }) => {
  return hits.map(item => {
    const { objectID, image, name } = item
    return (
      <article key={objectID}>
        <Image fluid={image} className="img" />
        <h4>{name}</h4>
      </article>
    )
  })
})
Example #2
Source File: index.jsx    From elliot-serverless-ecommerce with MIT License 6 votes vote down vote up
Results = connectHits(({ hits }) =>
	hits.length > 0 ? (
		hits.map(hit => <Hit key={hit.objectID} hit={hit} />)
	) : (
		<Error>
			<FormattedMessage id="search.no_results" />
		</Error>
	)
)
Example #3
Source File: NpoOrganizationDropdownField.js    From website with MIT License 5 votes vote down vote up
CustomHits = connectHits(Results)
Example #4
Source File: index.js    From website with MIT License 5 votes vote down vote up
CustomHits = connectHits(Hits)
Example #5
Source File: RelatedSolutions.js    From plataforma-sabia with MIT License 5 votes vote down vote up
RelatedSolutions = ({ technology }) => {
	const { colors } = useTheme();
	const { t } = useTranslation(['common']);
	const [searchLength, setSearchLength] = useState({
		technology: 0,
		service: 0,
	});

	const filters = useMemo(() => {
		const keywords = technology.keywords
			.map((keyword) => `keywords:"${keyword.term.trim()}"`)
			.join(' OR ');

		return keywords.length ? `NOT objectID:"${technology.objectID}" AND (${keywords})` : '';
	}, [technology.keywords, technology.objectID]);

	return (
		<>
			{(!!searchLength.technology || !!searchLength.service) && (
				<SectionTitle bgColor={colors.whiteSmoke} noMargin>
					{t('common:relatedSolutions')}
				</SectionTitle>
			)}

			<AlgoliaSearchProvider indexName={algoliaDefaultConfig.technology.indexName}>
				<>
					<Configure filters={filters} maxFacetHits={4} />
					<Results
						type="technology"
						current={searchLength.technology}
						onChange={setSearchLength}
					/>

					{!!searchLength.technology && (
						<SolutionsWrapper bgColor={colors.whiteSmoke} overwriteAlgoliaStyles>
							<Hits
								hitComponent={connectHits(({ hit }) => (
									<SolutionCard type="technology" data={hit} />
								))}
							/>
						</SolutionsWrapper>
					)}
				</>
			</AlgoliaSearchProvider>

			<AlgoliaSearchProvider indexName={algoliaDefaultConfig.service.indexName}>
				<>
					<Configure filters={filters} maxFacetHits={4} />
					<Results
						type="service"
						current={searchLength.service}
						onChange={setSearchLength}
					/>

					{!!searchLength.service && (
						<SolutionsWrapper bgColor={colors.whiteSmoke} overwriteAlgoliaStyles>
							<Hits
								hitComponent={connectHits(({ hit }) => (
									<SolutionCard type="service" data={hit} />
								))}
							/>
						</SolutionsWrapper>
					)}
				</>
			</AlgoliaSearchProvider>
		</>
	);
}
Example #6
Source File: index.js    From website with MIT License 4 votes vote down vote up
TopDonations = ({ numberOfPosts, numberOfCategories }) => {
  const router = useRouter();
  const [topCategories, setTopCategories] = useState([]);

  useEffect(() => {
    getTopNCategories().then((categories) => {
      getTopNCategoriesFromAlgolia('donations').then(({ hits, facets }) => {
        if (facets['categories.id'] === undefined || Object.keys(facets['categories.id']).length === 0) {
          return;
        }
        const sorted = sortObjectEntries(facets['categories.id']);
        if (sorted.length >= numberOfCategories) {
          const topNCategoriesIds = sorted.slice(0, numberOfCategories);
          const topNCategories = categories.filter((category) => {
            if (topNCategoriesIds.includes(category.id)) {
              return true;
            }
            return false;
          });
          setTopCategories(topNCategories);
        } else if (sorted.length > 0 && sorted.length < numberOfCategories) {
          const topCategories = categories.filter((category) => {
            if (sorted.includes(category.id)) {
              return true;
            }
            return false;
          });
          setTopCategories(topCategories);
        }
      });
    });
  }, []);

  const getTopNCategories = async () => {
    const rawCategories = await api.categories.getAll().catch((err) => console.error(err));
    return rawCategories.docs.map((doc) => doc.data());
  };

  const TopDonationsRow = ({ hits, category }) => {
    const categoryHref = `/donations/category/${category.id}`;
    const handleViewAllButton = (event) => {
      event.preventDefault();
      router.push(categoryHref);
    };
    const getScrollableWidth = () => document.getElementById(category.id).clientWidth;
    const handleScrollLeft = () => (document.getElementById(category.id).scrollLeft -= getScrollableWidth());
    const handleScrollRight = () => (document.getElementById(category.id).scrollLeft += getScrollableWidth());
    return (
      <TopDonationCardsContainer key={category.id}>
        <CategoryHeader>
          <LeftAnchor>
            <Text size="normal" weight="bold">
              {category.name}
            </Text>
          </LeftAnchor>
          <RightAnchor>
            <Button size="small" asComponent={GreySubtleButton} onClick={handleViewAllButton}>
              <BlackText size="small">View all</BlackText>
            </Button>
          </RightAnchor>
        </CategoryHeader>
        <CarouselContainer>
          <Desktop>
            <CarouselScrollButton direction="left" size="normal" onClickHandler={handleScrollLeft} />
          </Desktop>
          <DonationsRow id={category.id} className="scrollableDonation">
            <Stack direction="row" align="start" spacing="extraLoose">
              {hits.map((donation) => {
                const donationPostHref = `/donations/${donation.objectID}`;
                const profileHref = `/profile/${donation.user.userId}`;
                const validPeriod = `${getFormattedDate(donation.validPeriodFrom)} - ${getFormattedDate(
                  donation.validPeriodTo
                )}`;
                return (
                  <DonationCard
                    key={`${category.id}-${donation.objectID}`}
                    name={donation.user.userName}
                    title={donation.title}
                    description={donation.description}
                    profileImageUrl={donation.user.profileImageUrl}
                    postedDateTime={donation.postedDateTime}
                    coverImageUrl={donation.coverImageUrl}
                    postHref={donationPostHref}
                    profileHref={profileHref}
                    validPeriod={validPeriod}
                    itemCondition={donation.itemCondition}
                    categoryId={category.id}
                    categoryName={category.name}
                  ></DonationCard>
                );
              })}
            </Stack>
          </DonationsRow>
          <Desktop>
            <CarouselScrollButton direction="right" size="normal" onClickHandler={handleScrollRight} />
          </Desktop>
        </CarouselContainer>
      </TopDonationCardsContainer>
    );
  };

  const TopCategories = connectHits(TopDonationsRow);

  return (
    <Stack direction="column" align="start" spacing="natural">
      {topCategories.map((category) => (
        <InstantSearch key={category.id} searchClient={searchClient} indexName="donations">
          <TopCategories category={category} />
          <Configure filters={getByCategoryIdAndStatus(category.id, 'pending')} hitsPerPage={numberOfPosts} />
        </InstantSearch>
      ))}
    </Stack>
  );
}
Example #7
Source File: index.js    From website with MIT License 4 votes vote down vote up
TopWishes = ({ numberOfPosts, numberOfCategories }) => {
  const router = useRouter();
  const [topCategories, setTopCategories] = useState([]);

  useEffect(() => {
    getAllCategories().then((categories) => {
      getTopNCategoriesFromAlgoliaWithExpireDateTime('wishes').then(({ hits, facets }) => {
        if (facets['categories.id'] === undefined || Object.keys(facets['categories.id']).length === 0) {
          return;
        }
        const sorted = sortObjectEntries(facets['categories.id']);
        if (sorted.length >= numberOfCategories) {
          const topNCategoriesIds = sorted.slice(0, numberOfCategories);
          const topNCategories = categories.filter((category) => {
            if (topNCategoriesIds.includes(category.id)) {
              return true;
            }
            return false;
          });
          setTopCategories(topNCategories);
        } else if (sorted.length > 0 && sorted.length < numberOfCategories) {
          const topCategories = categories.filter((category) => {
            if (sorted.includes(category.id)) {
              return true;
            }
            return false;
          });
          setTopCategories(topCategories);
        }
      });
    });
  }, []);

  const getAllCategories = async () => {
    const rawCategories = await api.categories.getAll().catch((err) => console.error(err));
    return rawCategories.docs.map((doc) => doc.data());
  };

  const TopWishesColumn = ({ hits, category }) => {
    const categoryHref = `/wishes/category/${category.id}`;
    const handleViewAllButton = (event) => {
      event.preventDefault();
      router.push(categoryHref);
    };
    return (
      <WishesColumn key={category.id}>
        <CategoryHeader title={category.name}></CategoryHeader>
        {hits.map((wish) => {
          const wishPostHref = `/wishes/${wish.objectID}`;
          const profileHref = `/profile/${wish.user.userId}`;
          return (
            <GroupWishCard
              key={`${category.id}-${wish.objectID}`}
              name={wish.organization.name}
              title={wish.title}
              description={wish.description}
              imageUrl={wish.user.profileImageUrl}
              postedDateTime={wish.postedDateTime}
              postHref={wishPostHref}
              profileHref={profileHref}
              categoryId={category.id}
              categoryName={category.name}
            />
          );
        })}
        <ViewAllButtonContainer>
          <Button size="small" asComponent={GreySubtleButton} onClick={handleViewAllButton}>
            <BlackText size="small">View all</BlackText>
          </Button>
        </ViewAllButtonContainer>
      </WishesColumn>
    );
  };

  const TopCategories = connectHits(TopWishesColumn);

  return (
    <Stack desktop={{ direction: 'row' }} direction="column" align="start" spacing="extraLoose">
      {topCategories.map((category) => (
        <InstantSearch key={category.id} searchClient={searchClient} indexName="wishes">
          <TopCategories category={category} />
          <Configure
            filters={getByCategoryIdAndStatusAndNotExpired(category.id, 'pending', Date.now())}
            hitsPerPage={numberOfPosts}
          />
        </InstantSearch>
      ))}
    </Stack>
  );
}
Example #8
Source File: index.js    From plataforma-sabia with MIT License 4 votes vote down vote up
SolutionList = ({
	indexName,
	searchState,
	resultsState,
	onSearchStateChange,
	onSearchParameters,
	widgetsCollector,
	institutionId,
}) => {
	const [searchLength, setSearchLength] = useState({
		technology: 0,
		service: 0,
	});
	const theme = useTheme();

	const filters = `institution_id:"${institutionId}"`;

	return (
		<AlgoliaSearchProvider
			indexName={indexName}
			searchState={searchState}
			resultsState={resultsState}
			onSearchStateChange={onSearchStateChange}
			onSearchParameters={onSearchParameters}
			widgetsCollector={widgetsCollector}
		>
			<ThemeProvider>
				<S.Wrapper>
					<S.Container>
						<S.Top>
							<S.Title>Vitrine tecnológica</S.Title>
							<DebouncedSearchBox placeholder="Qual solução você busca?" secondary />
							<S.SortWrapper>
								<HitsPerPage
									items={[
										{
											label: `${ITEMS_PER_PAGE} resultados por página`,
											value: ITEMS_PER_PAGE,
										},
									]}
									defaultRefinement={ITEMS_PER_PAGE}
								/>
							</S.SortWrapper>
						</S.Top>
						<S.Content>
							<Index indexName={algoliaDefaultConfig.technology.indexName}>
								<Configure filters={filters} />
								<Results
									type="technology"
									current={searchLength.technology}
									onChange={setSearchLength}
								/>

								{!!searchLength.technology && (
									<ScrollTo>
										<SolutionsWrapper
											containerPadding="3.2rem 0"
											header="Tecnologias em destaque"
											headerComponent="title"
											headerProps={{
												align: 'left',
												color: theme.colors.silver,
												centerInMobile: true,
											}}
											algoliaCustomCss={S.algoliaListCss}
											overwriteAlgoliaStyles
										>
											<Hits
												hitComponent={connectHits(({ hit }) => (
													<SolutionCard type="technology" data={hit} />
												))}
											/>
										</SolutionsWrapper>
										<Pagination />
									</ScrollTo>
								)}
							</Index>

							<Index indexName={algoliaDefaultConfig.service.indexName}>
								<Configure filters={filters} />
								<Results
									type="service"
									current={searchLength.service}
									onChange={setSearchLength}
								/>
								{!!searchLength.service && (
									<ScrollTo>
										<SolutionsWrapper
											containerPadding="3.2rem 0"
											header="Serviços em destaque"
											headerComponent="title"
											headerProps={{
												align: 'left',
												color: theme.colors.silver,
												centerInMobile: true,
											}}
											algoliaCustomCss={S.algoliaListCss}
											overwriteAlgoliaStyles
										>
											<Hits
												hitComponent={connectHits(({ hit }) => (
													<SolutionCard type="service" data={hit} />
												))}
											/>
										</SolutionsWrapper>
										<Pagination />
									</ScrollTo>
								)}
							</Index>
						</S.Content>
					</S.Container>
				</S.Wrapper>
			</ThemeProvider>
		</AlgoliaSearchProvider>
	);
}