Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variables for refetchQueries in Apollo

Tags:

reactjs

apollo

I am not sure what the best practice is to pass variables in refetchQueries options. In below example the variables is {id: this.props.item.id}

But passing this.props.item.id returned an error since MyComponent is not yet instantiated hence this.props is undefined.

function mapStateToProps(state) {
  return {
    item: state.item
  };
}

MyComponent = connect(mapStateToProps, matchDispatchToProps)(
  MyComponent
);

MyComponent = graphql(createItemImage, {
  name: "createItemImage",
  options: {
    refetchQueries: [
      {
        query: getEntity,
        variables: { id: this.props.item.id }
      }
    ]
  }
  })(MyComponent);

The id value will only be available during runtime.

Thanks in advance!

like image 522
iwan Avatar asked Apr 29 '18 07:04

iwan


Video Answer


1 Answers

This is what finally works, refer to ownProps and the order (connect statement should be after the graphql statement)

MyComponent = graphql(createItemImage, {
  name: "createItemImage",
  options: ownProps => ({
    refetchQueries: [
      {
        query: getEntity,
        variables: { id: ownProps.item.id }
      }
    ]
  })
})(MyComponent);

MyComponent = connect(mapStateToProps, matchDispatchToProps)(
  MyComponent
);
like image 92
iwan Avatar answered Oct 09 '22 13:10

iwan