【问题标题】:Apollo/graphQL: How to use optimistic UI for a mutation of a nested react component?Apollo/graphQL:如何将乐观 UI 用于嵌套反应组件的突变?
【发布时间】:2023-03-06 15:14:01
【问题描述】:

如下所示,我正在使用 graphQL 查询在 pages/article.js 的 nextJS 应用程序中获取我的数据。 这些数据被传递给另一个反应组件,它给了我一个复选框列表。

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

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

refetchQueries 替换为

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

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

我看不出我做错了什么。而这只是获得 Optimisic UI 的第一部分..

pages/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)

components/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)

【问题讨论】:

    标签: javascript reactjs react-apollo nextjs optimistic-ui


    【解决方案1】:

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

    这就是您对readQuery 的调用失败的原因,您需要提供对突变结果的解析而不是实际查询的query 参数,因此是TypeError: Cannot read property 'kind' of undefined

    您只需使用另一个标识符命名您的查询,例如 getQueryArticle

    【讨论】:

    • 哦,明白了。谢谢你。你能解释一下新更新函数的第二个参数吗? ({ data: { getArticle } })。这在我的情况下似乎没有内容,所以我认为它命名错误,我在问自己是否真的需要它......
    • 当然你可以自己调试它,像这样重写你的更新函数:update: (store, { data }) =&gt; { console.log(data); }你会发现数据对象中有一个字段通常以你的变异命名,其中包含变异结果。跨度>
    猜你喜欢
    • 2020-04-24
    • 2019-07-16
    • 2020-09-23
    • 2019-08-24
    • 2017-10-18
    • 2017-11-02
    • 2020-11-11
    • 2018-08-24
    • 2021-04-09
    相关资源
    最近更新 更多