как отправить форму с помощью мутации с ApolloClient? - PullRequest
0 голосов
/ 25 февраля 2019

Я создал образец формы Formik, используя antd.Теперь я добавляю мутацию с POST_MUTATION. Как отправить значения формы через formik.Здесь я вызвал handleSubmit в форме. Но это не называется?

 import React from 'react'
import { Formik, Field, Form } from 'formik';
import * as AntD from "antd";
import TextField from "./shared/TextField"
import { Mutation, graphql } from 'react-apollo'
import gql from 'graphql-tag'
import data from './shared/data'

const POST_MUTATION = gql`
  mutation PostMutation($username: String!, $email: String!, $password: String!){
    post(username: $username, email: $email, password: $password) {

      username
      email
      password
    }
  }
`


class FormikApollo extends React.Component {
  state = {
      username: '',
      email: '',
      password: '',
      data: {}
  }

  handleChange= (e) => {
        this.setState({
            [e.target.name] : e.target.value,
            data
        })
  }

  handleSubmit = () => {
   alert("called")
  }

И я добавляю форму formik, используя этот способ. Теперь я хочу передать значения формы, которые не были отправлены. Как отправитьзначения формы в formik?

form = props => {
            const { username, email, password  } = this.state;
            return (
                <div align="center">
                    <h3 align="center">Registration Form</h3>
                    <Mutation mutation={POST_MUTATION} variables={{ username, email, password }}>
                    { postMutation  => (
                    <Form onSubmit={(formikValues) => postMutation({ variables: formikValues })}>
                        <Row gutter={4}>
                            <Col span={12} push={5}>
                                <Field
                                    name="username"
                                    label="Name"
                                    placeholder="Enter a Name"
                                    component={TextField}
                                    formitemlayout={formItemLayout} 
                                    value={this.state.username}
                                    onChange={this.handleChange}
                                    />

                                <Field
                                    name="email"
                                    label="Email"
                                    placeholder="Enter an Email"
                                    component={TextField}
                                    formitemlayout={formItemLayout} 
                                    value={this.state.email}
                                    onChange={this.handleChange}
                                    />

                                <Field
                                    name="password"
                                    label="Password"
                                    type="password"
                                    placeholder="Enter a Password"
                                    component={TextField}
                                    formitemlayout={formItemLayout} 
                                    value={this.state.password}
                                    onChange={this.handleChange}
                                  />


                                 <Button type="submit" onClick={JSON.stringify(postMutation)}>Submit</Button>


                            </Col>
                        </Row>
                    </Form>
                    )}

                    </Mutation>
                </div>
            )
        }


        render() {

            return (
                <div align="center">
                    <Formik
                        initialValues = {{
                          username: '',
                          email:'',
                          password:''
                        }}
                        render={this.form}
                    />

                </div>
            )
        }

    }

    export default FormikApollo

Ответы [ 3 ]

0 голосов
/ 05 апреля 2019

Я выбрал другой подход, используя как formik , так и apollo mutation .Вместо того, чтобы использовать другой тег мутации (так надоело их, кстати! Чтобы ваш код выглядел грязным так быстро), я использовал this.props.mutate () в функции.

Ваша мутацияможно найти в подпорках, когда вы экспортируете свой компонент с этой мутацией под влиянием graphql.Вы увидите это чуть позже.

Вот так выглядит моя форма внутри главной функции render () моего компонента

< Formik
initialValues = {
  {
    title: '',
  }
}
onSubmit = {
  this.submitMutation // my own function
}
render = {
  this.renderForm // my own function that just returns views and texts tags
}
validationSchema = {
    Yup.object().shape({
      title: Yup
        .string()
        .required('title is required'),
    })
  } >

  <
  /Formik>

Ниже представлена ​​моя мутационная функция submit, вызываемая formik

submitMutation = () => {
  return this.props.mutate({
    variables: {
      title: this.state.title,
    },
  })
}
И в конце сделайте это

export default graphql(addBillMutation)(CreateBill);

Код OverAll .., пожалуйста, отрегулируйте его под свой костюм

import React from 'react';
import {
    StyleSheet, Text, Image, View, TextInput, Picker, TouchableOpacity, ScrollView, KeyboardAvoidingView
} from 'react-native';

import Header from './header';
import { graphql } from 'react-apollo';
//import mutation query from queries
import { getBillsQuery, addBillMutation } from './queries/queries';
import { Formik } from 'formik';
import * as Yup from 'yup';

class CreateBill extends React.Component<any, any>  {
    constructor(props: any) {
        super(props);
        this.state = {
            title: "",
            loading: false,
        }
        this.submitMutation = this.submitMutation.bind(this);
    }

    submitMutation = () => {
        return this.props.mutate({
            variables: {
                title: this.state.title,
            }
        })
    }

    _handleSubmit = async (values: any) => {
        //setting values here, when form is already validated by yup in formika
        this.setState({
            title: values.title,
        });
        try {
            //set loading to true before sending request
            this.setState({ loading: true });
            await this.submitMutation()
                .then(({ data }) => {
                  //response handling
                }).catch((error) => {
                    this.setState({ loading: false });
                    //error handling
                });
        } catch (error) {
            //handle error
        }
    }

    renderForm = (formikProps: any) => {
        const {
            values, handleSubmit, handleBlur, handleChange, errors,
            touched, isValid, isSubmitting
        } = formikProps;

        return (

                <ScrollView>
                            <View>
                                        <TextInput
                                            style={styles.input}
                                            value={values.title}
                                            placeholder="title goes here"
                                            onChangeText={handleChange('title')}
                                            onBlur={handleBlur('title')}
                                        />
                                    </View>
                                        {(touched.title && errors.title) ? touched.title && errors.title : "Required"}
                                    </Text>
                                </View>
                                        
                            </View>
                </ScrollView>
        );
    }
    render() {
        return (
            <View>
                <Header />
                <View>

                    <Formik
                        initialValues={{ title: ''}}
                        onSubmit={this._handleSubmit}
                        render={this.renderForm}
                        validationSchema={Yup.object().shape({
                            title: Yup
                                .string()
                                .required('title is required'),
                        })}
                    >

                    </Formik>
                </View>
            </View>
        );
    }
}

export default graphql(addBillMutation)(CreateBill);
0 голосов
/ 05 апреля 2019

Ваш подход правильный.Лучше обернуть весь компонент в мутацию и использовать его как реквизит.Это простой компонент регистра.Я использую машинопись, если вам трудно следовать синтаксису.

Рабочий пример с ant-design и graphql (Typescript): https://github.com/benawad/graphql-typescript-stripe-example

Youtube Series: https://www.youtube.com/watch?v=G-Kj8Re6spA&list=PLN3n1USn4xllF5t1GZhEwFQNDnStgupdB

import { Field, Formik } from "formik";
import React from "react";
import Layout from "../components/Layout";

import { RegisterMutationVariables, RegisterMutation } from "../../schemaTypes";

const registerMutation = gql`
  mutation RegisterMutation($email: String!, $password: String!) {
    register(email: $email, password: $password)
  }
`;

export default () => {
  return (
    <Layout title="Register page">
      <Mutation<RegisterMutation, RegisterMutationVariables>
        mutation={registerMutation}
      >
        {register => (
          <Formik
            validateOnBlur={false}
            validateOnChange={false}
            onSubmit={async (data, { setErrors }) => {
              try {
                const response = await register({
                  variables: {
                    data
                  }
                });
                console.log(response);
              } catch (err) {
                console.log(err)
              }
            }}
            initialValues={{
              email: "",
              password: ""
            }}
          >
            {({ handleSubmit }) => (
              <form onSubmit={handleSubmit}>
                <Field
                  name="email"
                  placeholder="email"
                  component={InputField}
                />
                <Field
                  name="password"
                  placeholder="password"
                  type="password"
                  component={InputField}
                />
                <button type="submit">submit</button>
              </form>
            )}
          </Formik>
        )}
      </Mutation>
    </Layout>
  );
};
0 голосов
/ 25 февраля 2019

Ну, форматирование кода немного затрудняет просмотр вашего кода, однако в целом вы можете поместить форму внутри мутации и использовать функцию мутации в качестве функции отправки формы следующим образом:

<Form onSubmit={(formikValues) => postMutation({ variables: formikValues })}>
...