question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

onSuccess callback & GraphQL

See original GitHub issue

Is it possible to call a function on the component where the form is imported and displayed when I submit the form and validation passed?

I have some higher order components on my components (for example I’m using react-apollo for handling GraphQL requests) that bind certain methods to this.props that I don’t have access to in the onSuccess method of the form, because that is not a real react component.

I’d rather have the onSuccess method live in the Component where it get’s used

LoginForm.js

import validatorjs from 'validatorjs';
import MobxReactForm from 'mobx-react-form';

const plugins = { dvr: validatorjs };

const fields = [{
  name: 'email',
  label: 'Email',
  rules: 'required|email',
}, {
  name: 'password',
  label: 'Password',
  type: 'password',
  rules: 'required',
}];

class LoginForm extends MobxReactForm {
  onSuccess = (form) => {
    // i have no access to my login mutation here 
    console.log('Form Values!', form.values());
  }

  onError = (form) => {
    // get all form errors
    console.log('All form errors', form.errors());
    // invalidate the form with a custom error message
    form.invalidate('This is a generic error message!');
  }
}

export default new LoginForm({ fields }, { plugins });

Login.js

import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { inject, observer } from 'mobx-react';
import { gql, graphql } from 'react-apollo';
import cx from 'classnames';
import s from './Login.css';
import form from './LoginForm';
[... more imports]

class Login extends React.Component {
  static propTypes = {
    login: React.PropTypes.func.isRequired,
  }

  // I'd like to call this method on submit
  tryLogin = (form) => {
    this.props.login({
      email: ....,
      password: ....,
    })
    .then(() => {
      ... success
    })
    .catch(() => {
      ... error
    });
  }

  render() {
    return (
      <Page>
        <PageHeader />
        <PageInner>
          <GridColumn color={2} third>
            <div className={s.content}>
              <h1 className={cx('h2 p-b-2', s.headlineSpace)}>
                login
              </h1>
              <form onSubmit={form.onSubmit}>
                {form.error ? <Alert>{form.error}</Alert> : null}

                <Input field={form.$('email')} />
                <Input field={form.$('password')} />

                <div className={s.submit}>
                  <Button type="submit" onClick={form.onSubmit}>Login</Button>
                </div>
              </form>
            </div>
          </GridColumn>
        </PageInner>
      </Page>
    );
  }
}

const login = gql`
  mutation login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      id
      email
      token
    }
  }
`;

export default inject('store')(graphql(login, { name: 'login' })(withStyles(s)(observer(Login))));

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
mxmtskcommented, Mar 29, 2017

thank you @foxhound87, Overriding validation handlers is exactly what I was looking for. I missed that in the documentation 😃

0reactions
foxhound87commented, Apr 3, 2017

@kitze now the built-in event handlers are able to also handle promises, if you use them you can track the new submitting observable prop.

Read more comments on GitHub >

github_iconTop Results From Across the Web

onSuccess() for Apollo React Hooks | by Draj K - Medium
Recently working on a project with React and GraphQL, My team felt a need to have onSuccess() callback in addition to onError() and ......
Read more >
Hooks - Apollo GraphQL Docs
A callback function that's called when the query encounters one or more errors (unless errorPolicy is ignore ). This function is passed an...
Read more >
react-query: how to get the data from useQuery in onSuccess ...
The onSuccess callback function is called only when the data has been retrieved from the query. Carefully notice that this data is not...
Read more >
useMutation | TanStack Query Docs
onSuccess,. }) Options. mutationFn: (variables: TVariables) => Promise<TData>. Required; A function that performs an asynchronous task and returns a promise ...
Read more >
Mastering Mutations in React Query | TkDodo's blog
You'll also get the same nice callbacks that useQuery has: onSuccess, onError and onSettled. But that's about where the similarities end.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found