如何从组件访问突变数据?

时间:2019-05-05 12:26:14

标签: javascript graphql react-apollo apollo-client

这是我扩展组件的方式:

const ComponentWithMutation = graphql(GQL_MUTATION_ACTIVATE, 
    {
        options: (props) => ({
            variables: {
                foo: props.foo,
                bar: props.bar,
            },
        }),
    })(ActivateEmail);

现在在组件内部:

class ActivateEmail extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        const { match, mutate } = this.props;
        mutate({
            variables: { token: match.params.atoken },
        });
    }

    render() {
        return (
            <div>
                // I need to access data, error, loading here...
            </div>
        );
    }
}

我想访问data, error, loading。我该如何使用render方法?

1 个答案:

答案 0 :(得分:0)

关于阿波罗客户端docs,变异返回的诺言将返回变异信息,例如数据,错误,加载等。

因此代码应类似于:

constructor() {
    this.state = {
        dataLoading: true,
        dataLoadError: false,
    }
}

async componentDidMount() {
    try {
        const { match, mutate } = this.props;
        const { data: { yourMutationData }, error} = await mutate({
            variables: { token: match.params.atoken },
        });
        this.setState({
            dataLoading: false,
            data: yourMutationData 
        });
    }
    catch (err) {
        this.setState({
            dataLoading: false,
            dataLoadError: true,
        });
    }
}

或者您可以使用正常的承诺:

componentDidMount() {
    const { match, mutate } = this.props;
    mutate({
        variables: { token: match.params.atoken },
    })
    .then( (query) => {
        console.log(query); //here you should get the same result with the code above.
        this.setState({
            dataLoading: false,
            data: query.data.yourMutationData 
        });
    })
    .catch(err => {
        this.setState({
            dataLoading: false,
            dataLoadError: true,
        });
    })
}