登录状态在React,Apollo Client 2,Graphcool

时间:2018-01-28 12:13:23

标签: graphql apollo-client graphcool

我使用React,Apollo Client 2和Graphcool。我已经实现了一个登录表单。在登录页面上,根据客户端登录的天气显示登录表单或注销按钮。

我的代码有效,但没有被动更新。用户在刷新页面之前登录或注销任何更改。如何让我的代码被动?

import React from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this._confirm = this._confirm.bind(this);
    }

    _confirm = async e => {
        e.preventDefault();

        const result = await this.props.LoginMutation({
            variables: {
                email: '5@gmail.com',
                password: 'password',
            },
        });

        const token = result.data.authenticateUser.token;
        this._saveUserData(token);
    };

    _saveUserData = token => {
        localStorage.setItem('auth-token', token);
    };

    render() {
        return (
            <div>
                {this.props.LoginQuery.user ? (
                    <button onClick={() => localStorage.removeItem('auth-token')}>
                        Logout
                    </button>
                ) : (
                    <form onSubmit={this._confirm}>
                        <input type="email" id="email" />
                        <input type="password" id="password" />
                        <button type="submit">Login</button>
                    </form>
                )}
            </div>
        );
    }
}

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

const LoginQuery = gql`
    query AppQuery {
        user {
            id
        }
    }
`;

const LoginContainer = compose(
    graphql(LoginMutation, { name: 'LoginMutation' }),
    graphql(LoginQuery, { name: 'LoginQuery' }),
)(Login);

export default LoginContainer;

1 个答案:

答案 0 :(得分:0)

任何涉及UI的内容都不一定需要受到保护。因此,您可以轻松地使用状态或数据存储(例如redux,mobx等)来触发对UI的更新。

如果您希望使用GraphQL根据突变对UI进行反应性更新。我诚实地建议实施Subscriptions,它将为您提供您正在寻找的那种反应式数据流。

Subscriptions ~ Apollo Client