Giter Site home page Giter Site logo

charlypoly / react-apollo-form Goto Github PK

View Code? Open in Web Editor NEW
195.0 4.0 15.0 1.53 MB

Build React forms based on GraphQL APIs.

License: MIT License

JavaScript 1.93% HTML 0.20% TypeScript 97.87%
react graphql-api apollo mutations form forms reactforms graphql

react-apollo-form's Introduction

<ApolloForm> https://img.shields.io/circleci/project/github/wittydeveloper/react-apollo-form.svg https://img.shields.io/npm/v/react-apollo-form.svg https://img.shields.io/npm/dt/react-apollo-form.svg

Build React forms based on GraphQL APIs.


The library is currently under active rewriting, please see this ticket for updates


https://s3.eu-west-2.amazonaws.com/github-oss/react-apollo-form/read-me-demo-preview.png


To get started more easily, please read Getting started: build a GraphQL Form in 5 minutes


Pre-requisites

  • apollo-codegen (globally)
  • react@^15
  • react-apollo@^15

Optionally

  • typescript@^2.8.4

Installation

Install package

  • install yarn add react-apollo-form

Add script to your project

  • add to your package.json, at the scripts section :
{
    "scripts": {
        "react-apollo-form": "react-apollo-form fetch-mutations <graphql_endpoint> <outpurDir>"
    }
}

This script will generated 3 files needed by <ApolloForm>:

  • schema.json (GraphQL Introspection Query result as JSON)
  • mutations.d.ts (all available mutations names as TypeScript type definition)
  • apollo-form-json-schema.json (GraphQL Schema as JSON Schema)

Tips: you can change the output directory of theses with the second argument or -o option


Usage

Once the files generated, we can setup a Form.

import * as React from 'react';
import gql from 'graphql-tag';
import { configure } from 'react-apollo-form';
import { client } from './apollo';
import { applicationFormTheme } from './core/forms/themes/application';


const jsonSchema = require('./core/apollo-form-json-schema.json');

export const ApplicationForm = configure<ApolloFormMutationNames>({
    // tslint:disable-next-line:no-any
    client: client as any,
    jsonSchema,
    theme: applicationFormTheme
});

<ApplicationForm
    config={{
        mutation: {
            name: 'create_todo',
            document: gql`mutation {...}`
        }
    }}
    data={{}}
/>

API

ApolloForm is based on the amazing Mozilla library react-jsonschema-form. Most of the questions regarding JSON Schema, validations or rendering are in react-jsonschema-form documentation

To get started more easily, please read Getting started: build a GraphQL Form in 5 minutes

The following subjects are specific to ApolloForm:


Q&A

  • Can I make ApolloForm works with many GraphQL endpoints?

Yes, just setup multiple scripts in your project package.json with one output folder per endpoint, then just configure a "component form" for each endpoint

  • Where can I find some documentation about widgets, fields or theming in general?

Please take a look at the react-jsonschema-form documentation that will answers 90% of the rendering questions. If not, please take a look at Theming


Architecture

General

The idea is to build forms using mutations from the GraphQL API.

ApolloForm is "just" a wrapper around react-jsonschema-form.

It brings some "embed" features:

  • JSON schema generation from GraphQL Schema
  • conditionals forms
  • form rendering customisation with render props
  • build JSON Schema with functions (with functional-json-schema)

GraphQL to JSON Schema

See graphql-2-json-schema package.

react-apollo-form's People

Contributors

charlypoly avatar lukasluecke avatar renovate-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-apollo-form's Issues

No way to set FormContext

The FormContext is explicitly set within FormRenderer without allowing for the component consumer to set/override any values. This makes it very difficult to base on field off of another, such as updating a state/province dropdown to display states once a country has been selected.

The formContext object
You can provide a formContext object to the Form, which is passed down to all fields and widgets (including TitleField and DescriptionField). Useful for implementing context aware fields and widgets.

From: https://react-jsonschema-form.readthedocs.io/en/latest/advanced-customization/#the-formcontext-object

Bug? Wrong post data sent compared to Apollo form

I'm so close! The form is rendered correctly, but the post message is "off" ;)

The post message that works (from Apollo Mutation Form):

{
  "operationName": "createSite",
  "variables": {
    "domain": "testestsetess",
    "clientMutationId": 1
  },
  "query": "mutation createSite($clientMutationId: String!, $domain: String!) {createSite(input: {clientMutationId: $clientMutationId,domain: $domain}) {id,__typename}}"
},

and the post message from react-apollo-form:

{
  "operationName": "createSite",
  "variables":{
    "input":{
      "domain":"testtesttest",
      "clientMutationId":"4"
    }
  },
  "query":"mutation createSite($clientMutationId: String!, $domain: String!) {  createSite(input: {clientMutationId: $clientMutationId, domain: $domain}) {    id    __typename  }}"
}

And the error message from react-apollo-form post:

{
  "errors": [{
      "message": "Variable '$clientMutationId' of required type 'String!' was not provided.",
      "category": "graphql",
      "locations": [{"line": 1, "column": 21}]
    },
    {
      "message": "Variable '$domain' of required type 'String!' was not provided.",
      "category": "graphql",
      "locations": [{"line": 1, "column": 49}]
    }]
}

I have a createSite mutation:

const createSiteMutationDocument = gql`
    mutation createSite($clientMutationId: String!, $domain: String!) {
        createSite(input: {clientMutationId: $clientMutationId,domain: $domain}) {
            id
        }
    }
`;

that works when tested in GraphiQL and react-apollo Mutation, but the same doesn't work in react-apollo-form...

My Apollo Mutation Form:

const CreateSite = () => {
    let input: any;

    return <Mutation mutation={createSiteMutationDocument}>
        {(createSite, { data }) => (
            <div>
                <form
                    onSubmit={e => {
                        e.preventDefault();
                        createSite({ variables: { domain: input.value, clientMutationId: 1 } });
                        input.value = "";
                    }}
                >
                    <input
                        ref={node => {
                            input = node;
                        }}
                    />
                    <button type="submit">Create Site</button>
                </form>
            </div>
        )}
    </Mutation>
};

And my react-apollo-form:

                <ApplicationForm
                    title="Create site form"
                    liveValidated={true}
                    config={{
                        mutation: {
                            name: 'createSite',
                            document: createSiteMutationDocument
                        }
                    }}
                />

Also, since the availeble mutations are already specified in apollo-form-json-schema.json, is it possible to not including the mutation/graphql query in ApplicationForm?

Bug: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Hi!

I'm trying to use ApolloForm in a new project... I have successfully downloaded the requred schemas and config files from my Graphql server, and I have been able to use ApolloClient to fetch some basic data (so the client works!)

But when adding a simple application form, I get a bunch of warnings when building the package, and a error in the javascript console.

My code:

import './index.scss';
import React from "react";
import ReactDom from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter} from 'react-router-dom';
import { ApolloProvider } from 'react-apollo';
import {client}ย from './utils/apollo'
import {Sites} from "./components/Site";
import {ApplicationForm} from "./utils/ApplicationForm";

const rootEl = document.getElementById('root');
const basename = rootEl.dataset.basename;

ReactDom.render(
<ApolloProvider client={client} >
        <BrowserRouter basename={basename}>
            <div>
                <h1>Hello world!</h1>
                <Sites/>
                <ApplicationForm
                    title="Create site form"
                    liveValidated={true}
                    config={{
                        mutation: {
                            name: 'create_site',
                            document: gql`
                            mutation create_site($clientMutationId: String!, $domain: String!, $name: String!) {
                                createSite(input: {clientMutationId: $clientMutationId,domain: $domain, name: $name}) {
                                    id
                                }
                            }`
                        }
                    }}
                    data={{}}
                    ui={{}}
                />
            </div>
        </BrowserRouter>
    </ApolloProvider>,
    rootEl
);

registerServiceWorker();

And my ApplicationForm

import * as React from 'react';
import { configure } from 'react-apollo-form';
import { client } from './apollo';
import jsonSchema from '../../schemas/apollo-form-json-schema.json';

export const ApplicationForm = configure({
    client: client,
    jsonSchema
});

For references, my <Sites /> (that works):

import gql from 'graphql-tag';
import React from "react";
import { Query } from 'react-apollo';

const GET_SITES = gql`
    {
        sites {
            edges {
                node {
                    domain                    
                    id
                }
            }
        }
    }
`;

export const Sites = ({ onSiteSelected }) => (
    <Query query={GET_SITES}>
        {({ loading, error, data }) => {
            if (loading) return 'Loading...';
            if (error) return `Error! ${error.message}`;
            if (data) console.log(data);

            return (
                <select name="site" onChange={onSiteSelected}>
                    {data.sites.edges.map(item => (
                        <option key={item.node.id} value={item.node.id}>
                            {item.node.domain}
                        </option>
                    ))}
                </select>
            );
        }}
    </Query>
);

The error message I get is this one:

index.js:3 Uncaught Error: Cannot find module "."
    at webpackMissingModule (index.js:3)
    at ./node_modules/react-apollo-form/dist/index.js (index.js:3)
    at Object../node_modules/react-apollo-form/dist/index.js (index.js:9)
    at __webpack_require__ (bootstrap fbc5d3454bc15328c70b:19)
    at Object../assets/admin/utils/ApplicationForm.js (admin.6f0202b5.js:337)
    at __webpack_require__ (bootstrap fbc5d3454bc15328c70b:19)
    at Object../assets/admin/index.js (admin.6f0202b5.js:147)
    at __webpack_require__ (bootstrap fbc5d3454bc15328c70b:19)
    at bootstrap fbc5d3454bc15328c70b:62
    at bootstrap fbc5d3454bc15328c70b:62

And my build log:

 I  6 files written to public/build
 WAIT  Compiling...                                                                                                                                                           15:10:56

 WARNING  Compiled with 5 warnings                                                                                                                                            15:10:58

 warning  in ./node_modules/react-apollo-form/dist/lib/forms/utils.js

11:24-31 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

 warning  in ./node_modules/react-apollo-form/dist/lib/forms/component.js

21:24-31 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

 warning  in ./node_modules/react-apollo-form/dist/lib/forms/renderers.js

21:24-31 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

 warning  in ./node_modules/react-apollo-form/dist/index.js

3:24-31 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

 warning  in ./node_modules/react-apollo-form/dist/lib/forms/definitions.js

3:24-31 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

I would really appreciate some pointers on how to proceed! :)

[Question]: Support for react-i18n

Hi,

I think this library could be very useful. Thank you!
Have you encountered a use case to support react i18n?
Is there an implementation available as I think this is a common use case?

Thanks.

Get result of the mutation

Great library! Thanks, should save me tons of work :)

I just can not figure out how to access the result of the mutation after a successful submit. Do I need to access Apollo client directly?

no such file or directory 'react-apollo-form\dist\lib\cli.js'

I'm trying to install this, but no luck. I got some Warnings and an error:

npm WARN deprecated [email protected]: The 'apollo-codegen' command has been replaced with the more-powerful 'apollo' CLI.

npm ERR! path ...\node_modules\react-apollo-form\dist\lib\cli.js npm ERR! enoent ENOENT: no such file or directory, chmod '...\node_modules\react-apollo-form\dist\lib\cli.js'

Maintenance state

As this package should be replaced by another. Can we have a hope on this package maintenability ?

We must finish the development of our application in this month, so we can't wait april for the new package.

And for all other people using this package, this could be an important point too.

theming question

how can I implement fields so one row is full with and other might bight be split into 2 or 3 rows? also select fields

Issue with theming

Hi,

This library looks great, I'm a keen follower of any work in the space using schemas to automate code. I see you're rewriting a new version, but doesn't seem to be much doco there yet. In the meantime thought I'd try this version on a small survey form project I have.

All good, managed to get things up and running with the default theme, but when I tried to put in the theme from the theme doco in your wiki, I get the following error when I type anything in the field. Apologies if this is more react-jsonschema related, but any hints would be greatly appreciated.

index.js:1375 Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components
in input (created by Input)
in div (created by Input)
in Input (at ApplicationForm.js:31)
in StringField (created by SchemaField)
in div (created by FormField)
in FormField (at ApplicationForm.js:14)
in FieldTemplate (created by SchemaField)
in SchemaField (created by ObjectField)
in div (at ApplicationForm.js:23)
in ObjectFieldTemplate (created by ObjectField)
in ObjectField (created by SchemaField)
in div (created by FormField)
in FormField (at ApplicationForm.js:14)
in FieldTemplate (created by SchemaField)
in SchemaField (created by ObjectField)
in div (at ApplicationForm.js:23)
in ObjectFieldTemplate (created by ObjectField)
in ObjectField (created by SchemaField)
in div (created by FormField)
in FormField (at ApplicationForm.js:14)
in FieldTemplate (created by SchemaField)
in SchemaField (created by Form)
in form (created by Form)
in Form (created by FormRenderer)
in FormRenderer (created by ApolloForm)
in div (created by ApolloForm)
in ApolloForm (at App.js:39)
in div (at App.js:38)
in App (at src/index.js:8)

Cheers
Paul

Form data disappears.

Trying to debug a couple things.

First: When I provide data it doesn't seem to fill out the form unless I go into react-apollo-form node_modules and compile the typescript manually since I'm not using typescript in my project.

Second: After compiling. It seems to fill out the form initially but immediately upon typing will cause the form to loose all data for values in a referenced part of the schema. Did something like this to debug: onChange={console.log}. It seems like the values are already lost by this point.

Going to dig more into the cleanData util.

Doesnt handle arrays in mutation

Your tool is very interesting !
After some experiment, I have manage to make it work against a schema containing such a mutation :

type Mutation {
    create_todo(todo: TodoInputType!): Todo
}

But It fails when I try to declare it with an array :

type Mutation {
    create_todo(todo: [TodoInputType!]): Todo
}

I do not mean the UI should seamlessly enable multiple entries (yet :-) ), I mean it should still work for one entry. Here is the error I get :

image

If I can be of any help on that one...

Dependency deprecation warning: apollo-codegen (npm)

On registry https://registry.npmjs.org/, the "latest" version (v0.20.2) of dependency apollo-codegen has the following deprecation notice:

The 'apollo-codegen' command has been replaced with the more-powerful 'apollo' CLI. Switch to 'apollo' to ensure future updates and visit https://npm.im/apollo#code-generation for more information.

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about apollo-codegen's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

IMPORTANT: react-apollo-form full rewrite on-going

Regarding the current state of the library and the growing demand on it, the react-apollo-form is currently under a "re-design" phase.

This may imply some upcoming breaking changes needed to stabilise the library.

We will keep you updated on this ticket.

Fill part of form with code

Hi!

I have a required clientMutationId that I want to fill programatically, is there a simple way of forcing ApplicationForm to use supplied data-field instead of asking the user to enter it?

const createSiteMutationDocument = gql`
    mutation createSite($input: createSiteInput!) {
        createSite(input: $input) {
            id
        }
    }
`;

ReactDOM.render(
    <ApplicationForm
        title="Todo Form"
        liveValidate={true}
        config={{
            mutation: {
                name: 'createSite',
                document: createSiteMutationDocument,
                variables: {input: {clientMutationId: "1"}}
            }
        }}
        data={{input:{clientMutationId: "2"}}}
    />
    , document.getElementById('root'));

I tried both data and variables without success

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Updating multiple npm lock files is deprecated and support will be removed in future versions.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @storybook/addon-knobs to v3.4.12
  • chore(deps): update dependency @types/graphql to v0.13.4
  • chore(deps): update dependency @types/storybook__react to v3.0.9
  • chore(deps): update dependency typescript to v2.9.2
  • chore(deps): update dependency @storybook/addon-console to v1.2.3
  • chore(deps): update dependency @types/lodash to v4.17.0
  • chore(deps): update dependency @types/node to v10.17.60
  • chore(deps): update dependency awesome-typescript-loader to v5.2.1
  • chore(deps): update dependency graphql-tools to v3.1.1
  • chore(deps): update dependency tslint to v5.20.1
  • chore(deps): update jest monorepo (@types/jest, jest)
  • fix(deps): update dependency react-jsonschema-form to v1.8.1 (react-jsonschema-form, @types/react-jsonschema-form)
  • fix(deps): update dependency yargs to v11.1.1 (yargs, @types/yargs)
  • fix(deps): update react monorepo to v16.14.0 (react, react-dom)
  • chore(deps): update dependency @storybook/addon-console to v3
  • chore(deps): update dependency @storybook/addon-knobs to v7
  • chore(deps): update dependency @types/node to v20
  • chore(deps): update dependency @types/storybook__react to v5
  • chore(deps): update dependency css-loader to v7
  • chore(deps): update dependency graphql-tools to v9
  • chore(deps): update dependency semantic-ui-react to v2
  • chore(deps): update dependency tslint to v6
  • chore(deps): update dependency tslint-react to v5
  • chore(deps): update dependency typescript to v5
  • chore(deps): update jest monorepo to v29 (major) (@types/jest, jest, ts-jest)
  • fix(deps): update dependency yargs to v17 (yargs, @types/yargs)
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

circleci
.circleci/config.yml
html
.storybook/preview-head.html
  • semantic-ui 2.2.12
npm
package.json
  • apollo-client ^2.3.1
  • apollo-codegen ^0.19.1
  • graphql-2-json-schema 0.1.0-1
  • json-schema ^0.2.3
  • lodash ^4.17.10
  • react ^16.4.0
  • react-apollo ^2.1.4
  • react-dom ^16.4.0
  • react-jsonschema-form ^1.0.3
  • yargs ^11.0.0
  • @storybook/addon-actions ^3.4.6
  • @storybook/addon-console ^1.0.0
  • @storybook/addon-knobs ^3.4.6
  • @storybook/react 4.0.0-alpha.8
  • @types/apollo-codegen ^0.16.0
  • @types/graphql ^0.13.1
  • @types/jest ^23.0.0
  • @types/json-schema ^6.0.1
  • @types/lodash ^4.14.109
  • @types/node ^10.1.4
  • @types/react-jsonschema-form ^1.0.4
  • @types/storybook__react ^3.0.7
  • @types/yargs ^11.0.0
  • apollo-cache-inmemory ^1.2.2
  • apollo-storybook-react ^0.1.3
  • awesome-typescript-loader ^5.0.0
  • babel-core ^6.26.3
  • css-loader ^0.28.11
  • functional-json-schema 0.0.2-3
  • graphql-tag ^2.9.2
  • graphql-tools ^3.0.2
  • jest ^23.1.0
  • semantic-ui-react ^0.80.2
  • ts-jest ^22.4.6
  • tslint ^5.10.0
  • tslint-react ^3.6.0
  • typescript ^2.9.1

  • Check this box to trigger a request for Renovate to run again on this repository

Cannot read property 'name' of null

I have setup everything according to documentation.but while running script 'npm run react-apollo-form' getting this error.
image
can you please help me regarding this.

graphql-2-json-schema 0.1.0-1 doesn't handle enums properly

When I generate a form with a schema field, your current version generates a json schema field with no type, and the form was missing the field.

When I rebuilt your library with the 0.1.1 version, the schema generated a form that worked. Can you release a version with the updated dependency?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.