使用Apollo客户端GraphQL查询和改变一个表格[英] Querying and Mutating a Form with Apollo Client GraphQL

本文是小编为大家收集整理的关于使用Apollo客户端GraphQL查询和改变一个表格的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

整个GraphQl范式对我来说是新的,通常与React Redux一起工作.我的要求是:

  1. 用户单击一个w/uid的行项目

  2. 我们打开一个表格来编辑此数据(带有先前保存的信息预处理)

  3. 我们然后编辑此数据并保存

我认为(2)&(3)将由A <Query><Mutation/><Query>类型的结构进行处理,但它不起作用,主要是因为查询中的设置状态将使textInputs控制受控输入...由<<<<Query>,我不能再编辑它.

除此之外,我已经阅读了GraphQL消除了Redux的需求,等等?因此,我不愿意四处张贴这个查询,并在中间件中浮动.

有什么想法吗?这必须是一个普遍的要求.其他人想到了什么?

推荐答案

您的数据应作为道具传递给任何将要渲染表单的组件.在该组件的构造函数内部,您然后根据道具设置初始状态.一个粗略的例子:

class FormComponent extends React.Component {
  constructor () {
    this.state = this.props.initialState
  }

  render () {
    // Render form using this.state and this.props.update
  }
}

<Mutation mutation={SOME_MUTATION}>
  {(mutate) => (
    <Query query={SOME_QUERY}/>
      {({ data, loading, error }) => {
        if (loading) return <LoadingIndicator/>
        if (error) return <ErrorComponent/>
        if (data) return <FormComponent initialValues={data.someQuery} update={mutate}/>
      }}
    </Query>
  )}
</Mutation>

突变可以进入查询内部或在FormComponent本身内部 - 这并不重要.在获得数据之前,我们不会渲染FormComponent,因此初始值将始终反映查询的结果.

本文地址:https://www.itbaoku.cn/post/1938135.html

问题描述

The whole GraphQL paradigm is new to me, usually working with React Redux. My requirements are:

  1. User clicks a Row Item w/ UID

  2. We open a form to edit this data (with previously saved information pre-populated)

  3. We then edit this data and save

I would think (2) & (3) would be handled by a <Query><Mutation/><Query> type of structure but it doesn't work, mainly because setting state in the Query will make the textinputs controlled inputs... controlled by <Query>, and I can no longer edit it.

Besides this, I've read that GraphQL removes the need for Redux, etc? So I'm reluctant to go around sticking this query in a middleware and propogating to Redux.

Any thoughts? This must be a common requirement. What have others came up with?

推荐答案

Your data should be passed down as a prop to whatever component will actually render the form. Inside that component's constructor, you then set the initial state based on the props. A rough example:

class FormComponent extends React.Component {
  constructor () {
    this.state = this.props.initialState
  }

  render () {
    // Render form using this.state and this.props.update
  }
}

<Mutation mutation={SOME_MUTATION}>
  {(mutate) => (
    <Query query={SOME_QUERY}/>
      {({ data, loading, error }) => {
        if (loading) return <LoadingIndicator/>
        if (error) return <ErrorComponent/>
        if (data) return <FormComponent initialValues={data.someQuery} update={mutate}/>
      }}
    </Query>
  )}
</Mutation>

The mutation could go inside the Query, or inside the FormComponent itself -- that bit doesn't really matter. We're not rendering the FormComponent until we have data, so the initial values will always reflect the results of the query.