Shane Da Silva
Shane Da Silva

Reputation: 519

Redux-Form with Apollo

I'm trying to find examples of Redux-Form used with Apollo and can't find anything. I have an existing Redux-Form component and I'd like to trigger to submit using my GraphQL mutation. How would that look?

Upvotes: 1

Views: 552

Answers (1)

magnat
magnat

Reputation: 407

I'm not sure if you still need it but here is one of possible solutions. Maybe not the best components composition but this simple example should help you or others to create own forms with redux-form and apollo.

In the simplest scenario we can have all in one component. Below there is some piece of code:

import React from 'react'
import { graphql, compose } from 'react-apollo' 
import { Field, reduxForm } from 'redux-form'
import { submitForm } from './somewhere' //you can also define mutation in this file

class ApolloForm extends React.Component {
  submitForm = (data) => {
    return this.props.submitForm({
      variables: {firstName: data.firstName, lastName: data.lastName}
    })
  }

  render() {
    const { handleSubmit, submitting, submitSucceeded } = this.props
    return (
      <form onSubmit={handleSubmit(this.submitForm)}>
        <Field
          name="firstName"
          component="input"
          type="text"
        />
        <Field
          name="lastName"
          component="input"
          type="text"
        />
        <button type="submit" disabled={submitting}>Submit</button>
        { submitSucceeded && <p>Sent!!!</p> }
      </form>
    )
  }
}

const ApolloForm = compose(
  graphql(submitForm, {name: 'submitForm'},
  reduxForm({form: 'ApolloForm'})
)(ApolloForm)

Upvotes: 2

Related Questions