Search code examples
relayjs

Search with Relay doesn't include new results due to local cache


I've implemented a search-as-you-type component in React and Relay. It's roughly the same setup as search functionality using relay

It works as intended with one exception. New results from the server never appear when I retype a search I've already performed on the client. I looks like Relay always goes to the local cache in this case.

So, for example, say I've searched for 'foo' and didn't find any results. Now, seconds later, another user on the website creates this 'foo', but Relay will never query the server since the cached response to the 'foo' search was an empty result.

Is there a pattern or best practice for this scenario?

The query is as follows. I call this.props.relay.setVariables to perform the search:

initialVariables: {
    search: '',
    hasSearch: false
},
fragments: {
    me: () => Relay.QL`
        fragment on Viewer {
            relationSearch(search: $search) @include(if: $hasSearch) {
                ... on User {
                    username
                }
            }
        }
    `
}

Solution

  • The answer seems to be to use this.props.relay.forceFetch with the search variables instead.

    See https://facebook.github.io/relay/docs/api-reference-relay-container.html#forcefetch

    Someone correct me if this isn't best practice.