使用阿波罗在graphql中传递变量的正确方法是什么?或者如何使用阿波罗在grapQL查询中传递状态

时间:2018-12-11 00:53:40

标签: redux graphql apollo

大家需要帮助,我被要求创建身份验证,我们将GraphQL用于后端。和GraphQL-apollo在我们的前端。我试图弄清楚如何从前端查询。这是我的代码。

// ! imported dependecies
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { graphql, compose } from 'react-apollo';

// ! imported files
import Input from '../Common/Input/input';
import Button from '../Common/Button/button';
import { login } from '../../reduxes/actions/loginAction';

// ! imported query
import { userLogin } from '../../util/graphQLQuery';


// email: "boo@boo.com", password: "password")
class Login extends Component {
  state = {
    email: '',
    password: '',
  };

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

  handleClick = () => {
    const { email, password } = this.state;
    this.props.login({ email, password });
  };

  render() {
    const { email, password } = this.state;
    return (
      <div>
        <Input
          value={email}
          onChange={this.handleChange}
          placeholder="email"
          name="email"
        />
        <Input
          value={password}
          onChange={this.handleChange}
          placeholder="password"
          name="password"
        />
        <Button onClick={this.handleClick}> Login </Button>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  state,
});

const mapDispatchToProps = (dispatch) => ({
  login: (args) => {
    console.log(args, 'dis');
    dispatch(login(args));

  }
});

export default compose(
  connect(
    mapStateToProps,
    mapDispatchToProps
  ),
  // graphql query from backend
  graphql(userLogin, {
    options: (props) => {
      return {
        variables: {
          email: props.state.credentials.email,
          password: props.state.credentials.password
        },
      }
    }
  })
)(Login);

在onload上,这将立即导出,并且我将遇到查询错误,因为在我的初始状态下,其''是一个空字符串。还有另一种查询方式吗?只是使用状态而不是道具?

graphql(userLogin, {
        options: (props) => {
          return {
            variables: {
              email: props.state.credentials.email,
              password: props.state.credentials.password
            },
          }
        }
      })

在我的后端上,尝试输入电子邮件和密码时会收到令牌,但在前端看不到它。顺便说一句,我也使用redux。

0 个答案:

没有答案