简体   繁体   中英

How to make props.relay.setVariables update my data?

I'm trying to use a search component's 'onChange' to filter results using this.props.relay.setVariables but nothing gets re-rendered. I'm also hoping that when it does filter, that it will still use the Shuffle component. We are making one trip to the DB up front, and all these subsequent relay queries are coming from a cache (not sure if that is pertinent).

const GamesScreen = React.createClass({
  propTypes: {
    viewer: PropTypes.object,
  },
  search (e) {
    let searchStr = e.target.value;
    this.props.relay.setVariables ({ query: searchStr}, onFetch);
  },

  onFetch (){
    // does something need to happn in here to actually filter and re-render?
  },
  getSubjects ()
    {
    return this.props.viewer.subjects.edges;
  },
  render ()
    {
    const games = this.getSubjects().map(game => {
      return (
        <div className="Game-container" key={game.node.name}>
          <Game game={game.node} />
        </div>
      );
    });

    return (
      <div className="GamesScreen">
        <TopContainer>
          <TopBar viewer={this.props.viewer} />
        </TopContainer>
        <MidBar viewer={this.props.viewer} />
        <input type="search" placeholder="Search" onChange={this.search} />
        <div className="GamesScreen-container">
          <Shuffle duration={300} fade>
            {games}
          </Shuffle>
        </div>
      </div>
    );
  },
});

export default Relay.createContainer(GamesScreen, {
  initialVariables: {
    query: '',
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        subjects(query: "", first: 5)
         {
          edges {
            node {
              name
            }
          }
        },
        ${TopBar.getFragment('viewer')},
      }
    `,
  },
});

You just need to use the variable in your fragment. In GraphQL, variables are used by prepending $ to the variable name, kinda like bash or whatever:

export default Relay.createContainer(GamesScreen, {
  initialVariables: {
    query: '',
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        subjects(query: $query, first: 5) // <-- USE $query TO MODIFY FRAGMENT AT RUNTIME
         {
          edges {
            node {
              name
            }
          }
        },
        ${TopBar.getFragment('viewer')},
      }
    `,
  },
});

For more details, see the docs about Relay Containers and variables here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM