search functionality using relay

本小妞迷上赌 提交于 2019-11-30 07:14:38

问题


How to implement a search functionality with relay?

So, the workflow is

  • user navigate to search form.

there should not be any query (as in relay container) when initializing the view.

  • user fills the field values, and press the action/search button.

a relay query is sent to the server

  • results are received from the server.

page displays it and relay reconciles the filtered results with local cache.

I have not seen an example of ad hoc query but only part of a relay container (which it resolves before component initialization). So, how to model it. should it be like a mutation?


回答1:


If I understand correctly you'd like to not send any query at all for the component until the user enters some search text, at which point the query should sent. This can be accomplished with the example posted by @Xuorig, with one addition: use GraphQL's @include directive to skip the fragment until a variable is set. Here's the extended example:

export default Relay.createContainer(Search, {
  initialVariables: {
    count: 3,
    query: null,
    hasQuery: false, // `@include(if: ...)` takes a boolean
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        # add `@include` to skip the fragment unless $query/$hasQuery are set
        items(first: $count, query: $query) @include(if: $hasQuery) {
          edges {
            node {
              ...
            }
          }
        }
      }
    `,
  },
});

This query will be skipped initially since the include condition is falsy. Then, the component can call setVariables({query: someQueryText, hasQuery: true}) when text input is changed, at which point the @include condition will become true and the query will be sent to the server.




回答2:


This is the way I've implemented simple search in my project:

export default Relay.createContainer(Search, {
  initialVariables: {
    count: 3,
    title: null,
    category: null,
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        items(first: $count, title: $title, category: $category) {
          edges {
            node {
              ...
            }
          }
        }
      }
    `,
  },
});

Your search form simply has to update the initialVariables using this.props.relay.setVariables and relay will query the new data.



来源:https://stackoverflow.com/questions/34346273/search-functionality-using-relay

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!