如何用react-apollo graphql确定突变加载状态

rma*_*her 14 reactjs graphql apollostack

2018年更新: Apollo Client 2.1添加了一个新的Mutation组件,用于添加加载属性.请参阅下面的@ robin-wieruch的答案以及此处的公告https://dev-blog.apollodata.com/introducing-react-apollo-2-1-c837cc23d926继续阅读原始问题,该问题现在仅适用于早期版本的Apollo.


使用(v0.5.2)中当前版本的graphql高阶组件react-apollo,我没有看到一种记录方式来通知我的UI突变正在等待服务器响应.我可以看到该软件包的早期版本将发送一个指示加载的属性.

查询仍然会收到如下所示的加载属性:http://dev.apollodata.com/react/queries.html#default-result-props

我的应用程序也使用redux,所以我认为一种方法是将我的组件连接到redux并传递一个函数属性,使我的UI进入加载状态.然后当我将graphql变异重写为属性时,我可以调用更新redux存储.

大致像这样:

function Form({ handleSubmit, loading, handleChange, value }) {
  return (
    <form onSubmit={handleSubmit}>
      <input
        name="something"
        value={value}
        onChange={handleChange}
        disabled={loading}
      />
      <button type="submit" disabled={loading}>
        {loading ? 'Loading...' : 'Submit'}
      </button>
    </form>
  );
}

const withSubmit = graphql(
  gql`
    mutation submit($something : String) {
      submit(something : $something) {
        id
        something
      }
    }
  `, 
  {
    props: ({ ownProps, mutate }) => ({
      async handleSubmit() {
        ownProps.setLoading(true);
        try {
          const result = await mutate();
        } catch (err) {
          // @todo handle error here
        }
        ownProps.setLoading(false);
      },
    }),
  }
);

const withLoading = connect(
  (state) => ({ loading: state.loading }),
  (dispatch) => ({
    setLoading(loading) {
      dispatch(loadingAction(loading));
    },
  })
);

export default withLoading(withSubmit(Form));
Run Code Online (Sandbox Code Playgroud)

我很好奇是否有一种更惯用的方法来告知用户界面该变异是"飞行中".谢谢.

Rob*_*uch 5

自从Apollo Client 2.1以来,偶然发现此问题的任何人都可以在Query and Mutation 组件的render props函数中访问这些属性。

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

const TOGGLE_TODO = gql`
  mutation ToggleTodo($id: Int!) {
    toggleTodo(id: $id) {
      id
      completed
    }
  }
`;

const Todo = ({ id, text }) => (
  <Mutation mutation={TOGGLE_TODO} variables={{ id }}>
    {(toggleTodo, { loading, error, data }) => (
      <div>
        <p onClick={toggleTodo}>
          {text}
        </p>
        {loading && <p>Loading...</p>}
        {error && <p>Error :( Please try again</p>}
      </div>
    )}
  </Mutation>
);
Run Code Online (Sandbox Code Playgroud)

注意:示例代码取自Apollo Client 2.1版本的博客文章。

  • 由于这是HTTP请求,因此您不知道其进度。您发送一个请求,然后等待响应返回。 (2认同)

cta*_*van 3

我已经在 github 上重新发布了这个问题,建议的解决方案是使用类似反应高阶组件的东西,就像您在原始问题中提出的那样。我做了类似的事情 \xe2\x80\x93 ,但没有使用 redux,尽管 \xe2\x80\x93如本要点中所述

\n\n

引用Tom Coleman在 github 问题上的回复:

\n\n
\n

在突变容器上包含加载状态实际上没有意义;如果你考虑一下,你可以同时调用两次突变——哪个加载状态应该传递给子进程?我的感觉是,一般来说,将命令式 (this.mutate(x, y, z)) 与声明式(props)事物混合起来并不好;它会导致无法解决的不一致。

\n
\n