Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relay Pagination: How to initialize "after" value?

So based on this comment here, I've been able to hack together a simple "paginating" component/container: https://github.com/facebook/graphql/issues/4#issuecomment-118162627

I say "hack" because that's just what I did.

I got it to work by taking a look at the edge cursors on the /graphql response in my browser. Problem is.. how do I make this work for the first "page" of items, when I have no "prior query" to work from?

I tried leaving after as undefined in my query, but I only got the following error:

Uncaught Invariant Violation: callsFromGraphQL(): Expected a declared value for variable, $curs.

It seems, if you define first and after in your container's fragment, then they're required parameters. But I have no value for after, so how in the world does one go about initializing this?

This example throws the error above:

export default Relay.createContainer(Widgets2, {
  initialVariables: {
    pageSize: 2
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on User {
        widgets(
          first: $pageSize,
          after: $curs
        ) {
          edges {
            cursor,
            node {
              id,
              name,
            },
          },
        },
      }
    `,
  },
});
//And in the React component:
nextPage () {
    let lastIndex = this.props.viewer.widgets.edges.length - 1
    this.props.relay.setVariables({
        curs: this.props.viewer.widgets.edges[lastIndex].cursor
    })
 }
like image 257
RavenHursT Avatar asked Dec 22 '15 00:12

RavenHursT


1 Answers

Good question. In Relay, a default value must be provided for all variables. If the value isn't known you can use null: in this case that would mean specifying curs: null in initialVariables. We require an explicit null to help ensure that developers haven't forgotten to specify a value.

like image 71
Joe Savona Avatar answered Sep 27 '22 21:09

Joe Savona