Preserve React component state with Relay.setVariables

284 views Asked by At

I'm working on an application using React with Relay and GraphQL. I've run into an issue where I need to preserve a component's state while changing relay variables.

For example, say I have the component state:

state = {
  to: '',
  from: '',
  body: '',
  ...
}

And I have a Relay container with the following fragment and variables:

initialVariables: {
  to: '',
  from: '',
},
fragments: {
  viewer: () => Relay.QL`
    fragment on viewer {
      ...
      thread(to: $to, from: $from)
    }
  `
}

The component has text fields for the to and from fields, with an onChange handler which also updates the relay variables

onChange = e => {
  const to = e.target.value;

  this.setState({ to });
  this.props.relay.setVariables({ to });
}

This causes the query to execute again, the component re-renders, and I lose any changes to my current component state.

The only solution I've found thus far is to keep this state in a parent component, and pass down the values and onChange handlers as props, but it would be nice to keep this all in the same component.

How can I call relay.setVariables without losing state?

1

There are 1 answers

0
Jack On BEST ANSWER

Both setVariables and setState take an optional second argument to run after the state has actually updated.

I think you want:

this.props.relay.setVariables({ to }, () => this.setState({ to }));

but perhaps the inverse.