如何在不丢失“this"上下文的情况下从 React 组件中写入 apollo 缓存? [英] How to write to apollo cache from within React component with out losing context of "this"

查看:17
本文介绍了如何在不丢失“this"上下文的情况下从 React 组件中写入 apollo 缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试从 react 组件中读取 apollo 缓存时遇到问题,突变工作并写入我的服务器并返回数据,但是当传递给我的更新函数时,它似乎丢失了在 inMemoryCache.js

中时的上下文
  • "apollo-cache-inmemory": "^1.2.5"
  • 反应阿波罗":^2.1.4"
  • "apollo-boost": "^0.1.7"
<块引用>

TypeError: 无法读取未定义的属性 'read'在 ./node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.readQuery

import React, { Component } from "react";从react-apollo"导入{graphql};从lodash/trim"导入修剪;从 '../components/author-form' 导入 AuthorForm;从../graphql/getPosts.query"导入ALL_AUTHORS;从../graphql/createAuthor.mutation"导入CREATE_AUTHOR;类 CreateAuthor 扩展组件 {状态 = {错误:假};提交(事件){event.preventDefault();const form = new FormData(event.target);常量数据 = {firstName: form.get("firstName"),姓氏:form.get("姓氏")};if (!data.firstName || !data.lastName) {返回 this.setState({ errors: true });}this.create({名字:修剪(数据.名字),姓氏:修剪(数据.姓氏)});}异步创建(变量){const { createAuthor } = this.props;this.setState({ 错误: false });尝试 {等待创建作者({变量,更新:(缓存,数据)=>this.updateCache(缓存,数据)})}赶上(e){this.setState({ 错误: true })}}updateCache({ readQuery, writeQuery }, { data: { createAuthor }, errors }) {如果(错误){返回;}const { allAuthors } = readQuery({查询:ALL_AUTHORS,默认值:{所有作者:[]}});/*eslint-disable*/console.log(allAuthors);}使成为() {返回 (<div><AuthorForm onSubmit={this.onSubmit.bind(this)}/><OnError/>

);}}导出默认 graphql(CREATE_AUTHOR, { name: "createAuthor" })(CreateAuthor);

是否与我将其绑定到 onSubmit 按钮有关?如果是这样,将函数附加到元素而不会丢失组件内 this 的上下文并仍然允许 apollo 缓存正常运行的正确方法是什么.

解决方案

我失去了上下文,因为我正在解构第一个参数.这就是我最终确定的.

当 ROOT_QUERY 对象上没有 allAuthors 时,它会抛出错误,因此将其添加到我的 return 语句中.

这感觉不像是更新缓存的理想方式不应该默认传递给 readQuery 的参数防止抛出错误.

 updateCache(cache, { data: { createAuthor }, errors }) {如果(错误 || !cache.data.data.ROOT_QUERY.allAuthors){返回;}const 查询 = ALL_AUTHORS;const { allAuthors } = cache.readQuery({询问,默认值:{所有作者:[]}});常量数据 = {allAuthors: allAuthors.concat([createAuthor])};cache.writeQuery({询问,数据});}

I'm having trouble trying to read from apollo cache from within a react component the mutation works and writes to my server and returns the data but when passed to my update function it seems to lose the context of this when in inMemoryCache.js

  • "apollo-cache-inmemory": "^1.2.5"
  • "react-apollo": "^2.1.4"
  • "apollo-boost": "^0.1.7"

TypeError: Cannot read property 'read' of undefined at ./node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.readQuery

import React, { Component } from "react";
import { graphql } from "react-apollo";
import trim from "lodash/trim";

import AuthorForm from '../components/author-form';

import ALL_AUTHORS from "../graphql/getPosts.query";
import CREATE_AUTHOR from "../graphql/createAuthor.mutation";

class CreateAuthor extends Component {
  state = {
    errors: false
  };

  onSubmit(event) {
    event.preventDefault();

    const form = new FormData(event.target);

    const data = {
      firstName: form.get("firstName"),
      lastName: form.get("lastName")
    };

    if (!data.firstName || !data.lastName) {
      return this.setState({ errors: true });
    }

    this.create({
      firstName: trim(data.firstName),
      lastName: trim(data.lastName)
    });
  }

  async create(variables) {
    const { createAuthor } = this.props;
    this.setState({ errors: false });

    try {
      await createAuthor({
        variables,
        update: (cache, data) => this.updateCache(cache, data)
      })
    } catch (e) {
      this.setState({ errors: true })
    }
  }

  updateCache({ readQuery, writeQuery }, { data: { createAuthor }, errors }) {
    if (errors) {
      return;
    }
    const { allAuthors } = readQuery({
      query: ALL_AUTHORS,
      defaults: {
        allAuthors: []
      }
    });
    /*eslint-disable*/ console.log(allAuthors);
  }

  render() {
    return (
      <div>
        <AuthorForm onSubmit={this.onSubmit.bind(this)}/>
        <OnError/>
      </div>
    );
  }
}

export default graphql(CREATE_AUTHOR, { name: "createAuthor" })(CreateAuthor);

is it to do with me binding this to the onSubmit button? if so what is the proper way to attach a function to a element without losing context of this within the component and still allow apollo cache to function properly.

解决方案

I was losing the context of this because I was deconstructing the first argument. this is what I settled on in the end.

It throw errors when there were no allAuthors on the ROOT_QUERY object so added it to my return statement.

this doesn't feel like an ideal way of updating the cache shouldn't default param passed to readQuery prevent the error thrown.

 updateCache(cache, { data: { createAuthor }, errors }) {
    if (errors || !cache.data.data.ROOT_QUERY.allAuthors) {
      return;
    }

    const query = ALL_AUTHORS;

    const { allAuthors } = cache.readQuery({
      query,
      defaults: {
        allAuthors: []
      }
    });

    const data = {
      allAuthors: allAuthors.concat([createAuthor])
    };

    cache.writeQuery({
      query,
      data
    });
  }

这篇关于如何在不丢失“this"上下文的情况下从 React 组件中写入 apollo 缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆