React InstantSearch connectStateResults for no results page

According to your documentation here: https://community.algolia.com/react-instantsearch/connectors/connectStateResults.html

I can determine if a query has no results by checking searchResults.nbHits, however, in my application, nbHits never reaches zero. There will be no hits and the component just won’t fire Hit , so it’ll remain at 1 making it impossible to render a No Results page. Please advise, code below:

import React from 'react'
import { connectHits, connectStateResults } from 'react-instantsearch/connectors'
import getClassification from '../../utils/getClassification'
import Cards from './Cards'

export const CardContainer = ({ hit, searchState, searchResults }) => {
  console.log('hit:', searchResults.nbHits)
  if (searchResults && searchResults.nbHits !== 0) {
    return <Cards {...{ hit, key: hit.universal_id, classification: getClassification(hit) }} />
  } else {
    return <p>Sorry, no items match your search</p>
  }
}

export default connectHits(connectStateResults(CardContainer))

Here’s an example that works, in my experience your code should also work, but maybe something else is going wrong. Can you try editing my sandbox to be closer to your situation where it doesn’t work anymore? Are you editing the query?

I’m also noticing you’re doing connectHits around that, it maybe is related to that, if you keep those two things separate like I did in my sandbox, it likely works

This worked, thank you!

1 Like