Setting state in the Query component of react-apollo

Andreas picture Andreas · May 20, 2018 · Viewed 10.9k times · Source

So, I'm trying to set an initial state for an edit component that gets data from the server and now should be editable in the component state. But when I try to do this:

<Query query={POST_QUERY} variables={{ id: this.props.match.params.id }}>
    {({ data, loading, error }) => {
      this.setState({ title: data.title })

I get stuck in an infinite loop since this is in render. Should I not use the component state with the query component? And if not, what is the alternative?

Answer

Daniel Rearden picture Daniel Rearden · May 20, 2018

Whatever component needs this data as state should be rendered inside the Query component, and then have the data passed down to it as a prop. For example:

class MyComponent extends React.Component {
  constructor (props) {
    this.state = {
      title: props.post.title
    }
  }
}

<Query query={POST_QUERY} variables={{ id: this.props.match.params.id }}>
  {({ data, loading, error }) => {
    <MyComponent post={data.post}/>
  }}
</Query>