Querying and Mutating a Form with Apollo Client GraphQL

All we need is an easy explanation of the problem, so here it is.

The whole GraphQL paradigm is new to me, usually working with React Redux. My requirements are:

  1. User clicks a Row Item w/ UID

  2. We open a form to edit this data (with previously saved information pre-populated)

  3. We then edit this data and save

I would think (2) & (3) would be handled by a <Query><Mutation/><Query> type of structure but it doesn’t work, mainly because setting state in the Query will make the textinputs controlled inputs… controlled by <Query>, and I can no longer edit it.

Besides this, I’ve read that GraphQL removes the need for Redux, etc? So I’m reluctant to go around sticking this query in a middleware and propogating to Redux.

Any thoughts? This must be a common requirement. What have others came up with?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Your data should be passed down as a prop to whatever component will actually render the form. Inside that component’s constructor, you then set the initial state based on the props. A rough example:

class FormComponent extends React.Component {
  constructor () {
    this.state = this.props.initialState
  }

  render () {
    // Render form using this.state and this.props.update
  }
}

<Mutation mutation={SOME_MUTATION}>
  {(mutate) => (
    <Query query={SOME_QUERY}/>
      {({ data, loading, error }) => {
        if (loading) return <LoadingIndicator/>
        if (error) return <ErrorComponent/>
        if (data) return <FormComponent initialValues={data.someQuery} update={mutate}/>
      }}
    </Query>
  )}
</Mutation>

The mutation could go inside the Query, or inside the FormComponent itself — that bit doesn’t really matter. We’re not rendering the FormComponent until we have data, so the initial values will always reflect the results of the query.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply