繁体   English   中英

Apollo / graphQL:如何使用开放式UI对嵌套的React组件进行突变?

[英]Apollo/graphQL: How to use optimistic UI for a mutation of a nested react component?

如下所示,我使用graphQL查询在pages/article.js /article.js中的nextJS应用程序中获取数据。 该数据被传递到另一个react组件,该组件为我提供了一个复选框列表。

选择一个复选框将调用一个变异,以将所选复选框的ID存储在数据库中。 为了更新内容,我使用refetchQueries再次调用主查询 ,这会将数据向下传递到当前组件。

到目前为止,一切正常。 现在,我想使用乐观的UI实时获取这些信息-这使我遇到了一些问题...

用替换refetchQueries

update: (store, { data: { getArticle } }) => {
  const data = store.readQuery({
    query: getArticle,
    variables: {
      id: mainID
    }
  })
  console.log(data)
}

使我遇到错误TypeError: Cannot read property 'kind' of undefined来自readQuery TypeError: Cannot read property 'kind' of undefined

我看不到我在做什么错。 这只是获得优化UI的第一部分。

页/ article.js

import Article from '../components/Article'

class ArticlePage extends Component {
  static async getInitialProps (context, apolloClient) {
    const { query: { id }, req } = context
    const initProps = { }

    // ...

    return { id, ...initProps }
  }

  render () {
    const { id, data } = this.props
    const { list } = data
    return (
      <Article
        mainID={id}
        list={list}
      />
    )
  }
}

export default compose(
  withData,
  graphql(getArticle, {
    options: props => ({
      variables: {
        id: props.id
      }
    })
  })
)(ExtendedArticlePage)

组件/ Article.js

import { getArticle } from '../graphql/article'
import { selectMutation } from '../graphql/selection'

export class Article extends Component {
  checkboxToggle (id) {
    const { mainID, checkboxSelect } = this.props

    checkboxSelect({
      variables: {
        id
      },
      refetchQueries: [{
        query: getArticle,
        variables: {
          id: mainID
        }
      }],

    })
  }

  render () {
    const { list } = this.props
    return (
      list.map(l => {
        return (<Checkbox onClick={this.checkboxToggle.bind(this, l.id)} label={l.content} />)
      }
    )
  }
}

export default compose(
  graphql(selectMutation, { name: 'checkboxSelect' })
)(Article)

您的更新代码中存在一个阴影变量问题,似乎您对查询和嵌套在data的变异结果都使用了相同的名称getArticle

这就是为什么你要调用readQuery失败,则query PARAMS您需要提供解析为基因突变的结果,而不是实际的查询,因此, TypeError: Cannot read property 'kind' of undefined

您只需要使用另一个标识符(如getQueryArticle来命名查询即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM