16

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!

iwan
  • 7,269
  • 18
  • 48
  • 66

2 Answers2

22

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
);
iwan
  • 7,269
  • 18
  • 48
  • 66
  • The documentation for the `{ query, variables }` object is at https://www.apollographql.com/docs/react/api/react/hooks/#refetchqueries – icc97 Aug 26 '23 at 05:08
4

You need to explicitly pass item.id variable to the component. Therefore add in function a variable naming id

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

export default MyComponent

Then when calling the component use the following syntax

<MyComponent id={this.props.item.id}>

Hope this helps

mindaJalaj
  • 448
  • 3
  • 11
  • sorry but this is not the problem. I understood I need to pass `item={id: 123}` in calling MyComponent e.g. ``... but it is failing at compiled time with below error `TypeError: Cannot read property 'item' of undefined` because `this.props` is undefined – iwan Apr 29 '18 at 07:41
  • Sorry! My bad i used this.props inside component, we must use id directly here in this case. No need to use it via this.props. Have updated the code. Note: since we are not extending our component from React , the component will not receive life cycle function and props variable – mindaJalaj Apr 29 '18 at 09:33